Using jquery to replace space

I am importing a facebook RSS feed and many posts have no name. Therefore, in this case, I want to pull some content from the body and use it as a name. The problem is that the contents of the body may look like this ...

Lorem ipsum<br>www.youtube.com<br>dolor sit amet. 

I can’t just remove the br tags because it will become a run in the sentence. I would rather replace tags with a single space or comma with a space. I tried the following code, but it does not seem to work.

 $('.teaser-title br').replaceWith(' '); 

Thoughts?

+6
source share
7 answers

Description

2 Possible problems

  • You do not have an element with the teaser-title class.
  • You do not wait until the DOM is fully buildt

It works anyway

Example

 <div class="teaser-title"> Lorem ipsum<br>www.youtube.com<br>dolor sit amet. </div> <script> $(function() { $('.teaser-title br').replaceWith(' '); }); </script> 

Check out jsFiddle

+11
source

Posting because it can be done! You can use CSS: P

(only works in webkit, therefore not recommended)

 .teaser-title br{ content:""; } .teaser-title br:after{ content:" "; } 

Live demo

+4
source
 $(function() { $(".teaser-title br").replaceWith("&nbsp;"); }); 
+2
source

I can’t just remove the br tags because it will become the launch of the sentence.

Since you are worried about fulfilling sentences, you can replace <br> with <wbr> s.

HTML5 describes <wbr> in this way:

The wbr element represents the ability to interrupt a line.

+1
source

You want to replace the contents as text, not as tags:

 $('.teaser-title').html($('.teaser-title').html().replace(/<br />/g,' ')) 
0
source

you are trying to replace an element, and you should only replace the innerHtml of the .teaser title if .teaser-title is your container element.

try it

 var container = $(".teaser-title").html(); var regex = /<br\s*[\/]?>/gi; $(".teaser-title").html(container.replace(regex, " ")); 
0
source

Your code works well. Here is another way:

 $('.teaser-title br').after(' ').remove(); //$('.teaser-title br').replaceWith(' '); // your solution works too! 

demonstration

0
source

Source: https://habr.com/ru/post/905862/


All Articles