Anjana Sharma
Anjana Sharma

Reputation: 4745

very tricky html characters as text

<span class="WorkingHours">
   M,W,Th,F 7:30 AM - 4:00 PM &lt;br /&gt;Tu 7:30 AM - 6:00 PM &lt;br /&gt;
</span>

will be rendered as this

M,W,Th,F 7:30 AM - 4:00 PM <br />Tu 7:30 AM - 6:00 PM <br />

Now i need to replace the &lt;br /&gt; as an empty space before it is rendered?? I already asked a similar question, but i underestimated the trickiness of this.. I did this

$('.WorkingHours').text().replace(/<br \/>/g, " ");

didn't work..can someone help me out of this?

Shouldn't this work?

$('.WorkingHours').text().replace(/&lt;br \&gt;/g, " "); 

Upvotes: 0

Views: 125

Answers (3)

Felix Kling
Felix Kling

Reputation: 816482

This will work:

$('.WorkingHours').text(function(i, text) {
    return text.replace(/<br\s*\/?>/g, " "); 
});

DEMO

In this case .html() would return the HTML entities (&lt;) whereas .text() returns the decoded characters (i.e. <). Given that,

$('.WorkingHours').text().replace(/<br \/>/g, " ")

actually works as well but you still have to assign the result back to the element.

See also my previous answer.


Regarding replacing the last <br /> with a different character: It might be possible with regular expressions, but in that case, I would just parse the text as HTML and perform the same operation as I showed in my previous answer:

var $content = $('<div />').html($('.WorkingHours').text());
$content 
 .find('br').last().replaceWith('.')
 .end().replaceWith(' ');

$('.WorkingHours').html($content.html());

DEMO

Upvotes: 2

charlietfl
charlietfl

Reputation: 171669

If you have html entities in markup try replacing those instead

   replace('&lt;br \/&gt;', ' ')

Looks like you were missing a "/"

Upvotes: 0

Eric Hodonsky
Eric Hodonsky

Reputation: 5897

you have to escape the HTML characters to complete the pattern...

replace(/\<br \/\>/g, " ");

Upvotes: 0

Related Questions