Javascript Regex替换HTML标记

Javascript Regex Replace HTML Tags

本文关键字:标记 HTML 替换 Regex Javascript      更新时间:2023-09-26

使用正则表达式有很多困难。

这就是我要做的…

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

把它交给

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

我试着做。。。

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

但这给出了错误的输出。jquery提供了更好的方法吗?

这是因为您转义了错误的内容,因为只需要转义反斜杠。

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

是的,jQuery确实提供了一种更好的方法。

有趣的读物第一

简单,优雅,解决您的具体问题。

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

jsFiddle

如果不需要正则表达式,就不要使用它们;只需替换字符串文字。

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

注意:这个解决方案完全适用于这个场景,我通常不反对使用正则表达式。

这必须完成以下工作:

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

尽管只有在没有具有某些属性(如<div id="foo1">)的标记的情况下,这才会起作用您不需要像在示例中那样转义<,而是需要转义/

一个简单的方法如下:

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

/<(|'/)div>/:匹配<div></div>

演示

注意.container是放置html的位置。

使用JQuery 的一个Liner

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

您可以使用一个简单的RegExp 来实现这一点

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

或者你可以做这个

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 )  
}

然后直接在字符串上调用它,如下所示

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

你会得到这个——"text<br> text <br> text <br> text <br>"

这将搜索字符串中以"<"开头的部分,其中包含介于"div/p/br"之间的一些文本,此外,如果标记以"/"结尾,最后是标记的">"结束。当您不确定元素是用大写还是小写书写时,忽略大小写会有所帮助。