3

我试图//在文档中找到(斜杠)并用span.

我试过了

var slashes = "//";
/slashes+/

所以输出应该是:

Hello There! I Am <span class="slashes">//</span> An Alien

使用 jQuery .replace():contains但没有任何反应,我对调节器表达式不熟悉,可以正确执行此操作。我该怎么做?

编辑:我尝试了什么: 这个问题的解决方案不起作用:

function slashes($el) {

   $el.contents().each(function () {
       dlbSlash = "//";
       if (this.nodeType == 3) { // Text only
           $(this).replaceWith($(this).text()
               .replace(/(dlbSlash)/gi, '<span class="slashes">$1</span>'));
       } else { // Child element
           slashes($(this));
       }

   });
}

slashes($("body"));
4

4 回答 4

3

您需要转义正则表达式中的斜杠。尝试

var mystring = "adjfadfafdas//dsagdsg//dsafda"
mystring.replace(/\/\//g,'<span class="slashes">\/\/</span>');

应该输出

"adjfadfafdas<span class="slashes">//</span>dsagdsg<span class="slashes">//</span>dsafda"

如果要替换 h2 和 p 标签中的斜杠,可以像这样循环遍历它们:

$('h2, p').each(function(i, elem) { 
    $(elem).text(
        $(elem).text().replace(/\/\//g,'<span class="slashes">\/\/</span>'));
});

不过,这将消除您在 p 和 h2 标签中可能拥有的任何其他 html 标签。

于 2012-09-19T17:48:51.150 回答
2

这是另一种方法

//Find html inside element with id content
var html = $('#content').html();
//Replace // with <span style='color:red'>//</span>
html = html.replace(/\/{2}/g,"<span style='color:red'>$&</span>");
//Return updated html back to DOM
$('#content').html(html);​

这是演示

于 2012-09-19T18:11:53.190 回答
2

我想你找对地方了。唯一要修复的是您的正则表达式:

.replace(/\/\//g, '<span class="slashes">$1</span>'));

关注文本节点(类型 3)很重要,而不是对可能破坏页面的正文 innerHTML 进行全局替换。

于 2012-09-19T18:21:29.280 回答
0

如果您只想对单个应用此类替换//,请使用

mystring = mystring.replace(/(\/{2})/g, "<span class=\"slashes\">$1</span>");

但是,如果您想将其应用于 2 个或更多斜杠,请使用

mystring = mystring.replace(/(\/{2,})/g, "<span class=\"slashes\">$1</span>");

但是如果你想将它应用于任何数量的斜杠(例如//////等),那么你需要使用

mystring = mystring.replace(/((?:\/{2})+)/g, "<span class=\"slashes\">$1</span>");

在这里测试代码。

于 2012-09-19T18:01:51.703 回答