使用正则表达式高效查找和替换正文中的模式

时间:2014-01-09 10:33:47

标签: jquery html regex replace

我要做的是替换网址和模式,例如###http://www.google.com###包含<a>标记包含的链接,例如<a href="http://www.google.com">Go There</a>

我面临的问题是这个网址和模式可以出现在我的网页的任何地方,并且它包含的元素总是不同的 - 这就是我所做的。

$('body').contents().each(function(){

  // Find the pattern.
  var element = $(this);
  var go_link = element.text().match("###(.*)###");

  // Replace the pattern with go there button.
  if(go_link && go_link[1] != '(.*)'){
    var pattern = go_link[0];
    var link = go_link[1];
    element.html(element.html().replace(pattern,'<a class="go_there_button" href="'+link+'">Go There</a>'));
  }

});

这有效http://jsfiddle.net/84T9u/但我觉得它效率稍低,因为它必须遍历<body>中的每个元素,并且我网站的每个页面上可能有数百个这样的链接模式。 / p>

我已经开始考虑使用:contains()选择器,我已经在SO上找到了一些扩展此方法以允许使用正则表达式的答案,但是我对{{1}的方式还不太了解方法有效。它会更高效,还是在功能上与我正在使用的:contains()非常相似 - 迭代所有元素以找到所需的文本或模式?

2 个答案:

答案 0 :(得分:1)

您可以使用以下代码:

$('body').contents().each(function(){

  // Find the pattern.
  var element = $(this);
  if(element.html()){
      element.html(element.html().replace(/###(.*)###/g,"<a class=\"go_there_button\" href=\"$1\">Go There</a>"));

  }

});

或简单地说:

$('body').html($('body').html().replace(/###(.*)###/g,"<a class=\"go_there_button\" href=\"$1\">Go There</a>"));

答案 1 :(得分:0)

不要迭代或使用任何繁重的XML方法,只需将HTML更改为字符串:

str = str.replace(/###(https?:\/\/.*?)###/gi, '<a class="go_there_button" href="$1">Go There</a>');
相关问题