Jason Biondo
Jason Biondo

Reputation: 834

What is the JavaScript regex for <br /> when it is HTML encoded?

What is the regex for the HTML encoded version of <br /> in JavaScript: &lt;br /&gt;

var edit_text = $(".edit_area").html().trim(),
    regex = /<br\s*[\/]?>/gi;  //This needs replacing

$(".edit_area").html(edit_text.replace(regex, "\n"));

Upvotes: 2

Views: 1539

Answers (1)

p.s.w.g
p.s.w.g

Reputation: 149050

Your pattern won't match encoded <br> elements because it has a plain < which doesn't match an encoded &lt;. Try this to handle html encoded elements:

regex = /&lt;br\s*\/?(&gt;|>)/gi; 

Note that the closing character of a tag doesn't have to be encoded, so my pattern handles allows either encoded (&gt;) or un-encoded (>) closing characters. You can extend this to handle both using a pattern like this:

regex = /(&lt;|<)br\s*\/?(&gt;|>)/gi; 

You can test it out here.

Upvotes: 3

Related Questions