Skip to content Skip to sidebar Skip to footer

Javascript Regex Replace Html Tags

Having a lot of difficulties using regex. Heres what i am trying to do... text
text
text
text
to turn it in

Solution 1:

That's because you're escaping the wrong thing, as only the backslash needs to be escaped.

newhtml = newhtml.replace(/<div>/g,'<br>');newhtml = newhtml.replace(/<\/div>/g,' ');

Solution 2:

Yes you are correct, jQuery does provide a better way of doing this.

An interesting read first.

Easy, elegant, solution to your specific problem.

$('div').replaceWith(function(){
  return"<br>"+$(this).html();
});​

jsFiddle

Solution 3:

Don't use regexes if you don't need them; just replace string literals.

text.replace("<div>","<br>").replace("</div>","");

Note: This solution applies exactly to this scenario, I don't normally have anything against using regular expresions.

Solution 4:

This must do the job:

text.replace(/(<\/?\w+?>)\s*?(<\/?\w+?>)|(<\/?\w+?>)/g,'<br>')

Though this will only work if there were no tags with some attributes like <div id="foo1"> You do not need to escape < as you did in your example, but instead you do need to escape /

Solution 5:

A simple way to do this is the following:

$('.container').html(function(i, html) {
    return html.replace(/<(|\/)div>/g, function(match) {
        return match == '<div>' ? '<br>' : '';
    });
});

/<(|\/)div>/: Matches <div> or </div>.

demo

Note: .container is where your html is placed.

Post a Comment for "Javascript Regex Replace Html Tags"