简体   繁体   中英

Javascript Regex Replace HTML Tags

Having a lot of difficulties using regex.

Heres what i am trying to do...

text<div> text </div><div> text </div><div> text </div>

to turn it in to

text<br> text<br>text<br>text

I've tryed doing...

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

but this gives the wrong output. Does jquery provide a better way of doing this?

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,' ');

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

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 /

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.

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.

一个使用JQuery的Liner

newhtml = $(newhtml ).text().split(' ').join('<br/>');

You can achieve this using a simple RegExp

output = inputText.replace(/<\\w{0,}\\W{0,}>|<\\W{0,}\\w{1,}>/ig, "With whatever you want it to be replaced with")

Or you can do this

String.prototype.replaceTags = function( replacementText )
{      
    var x = new RegExp( "(" + replacementText + ")+" , "ig");
    return this
           .replace( /<\w{0,}\W{0,}>|<\W{0,}\w{1,}>/ig, replacementText )
           .replace( x, replacementText )  
}

And then call it directly on the String as follows

"text<div> text </div><div> text </div><div> text </div>".replaceTags( "<br>" )

You'll get this -- "text<br> text <br> text <br> text <br>"

This will search for portions in the string which begin with the "<" contains some text in between "div/p/br" additionally if the tag is being ended by "/" and finally the ">" closing of the tag. The ignore case will help when you are not sure that the element is written in Upper or Lower case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM