JavaScript正则表达式替换HTML标签

3

我在使用正则表达式时遇到了很多困难。

这是我想要做的事情...

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

把它转化为
text<br> text<br>text<br>text

I've tryed doing...

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

但是这样会得到错误的输出。jQuery有更好的方法来完成这个任务吗?

1
你想替换仅 div 标签还是任何标签? - WhyNotHugo
just <div> text </div> to <br>text - Lemex
为什么不直接用<br>代替所有的<div>,然后删除剩余的</div>呢? - WhyNotHugo
我的意思是,替换字符串字面量,而不是使用正则表达式。 :) - WhyNotHugo
7个回答

7

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

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

2

是的,你说得对,jQuery提供了更好的解决方法。

可以先看一下这篇有趣的阅读

对于你的具体问题,有一个简单而优雅的解决方案。

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

jsFiddle


1

这一定能完成工作:

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

虽然这只适用于没有带有某些属性的标签,例如<div id="foo1"> 您不需要像示例中所做的那样转义<,但是您确实需要转义/


adiv>b/div>div>c/div>div>d/div> 这就是它返回的内容。 - Lemex

1

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

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

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

0
一个简单的方法是以下这样做:
$('.container').html(function(i, html) {
    return html.replace(/<(|\/)div>/g, function(match) {
        return match == '<div>' ? '<br>' : '';
    });
});

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

演示

注意.container 是您的 HTML 放置的位置。


0

使用 JQuery 的一行代码

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

0

您可以使用简单的正则表达式来实现这一点

output = inputText.replace(/<\w{0,}\W{0,}>|<\W{0,}\w{1,}>/ig, "用您想要替换的任何内容进行替换")

或者您也可以这样做

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"之间的部分,此外,如果标签以"/"结束,最后是">"关闭标签。当您不确定元素是大写还是小写时,忽略大小写将有所帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接