Efficient find and replace pattern in body text using regular expression

大兔子大兔子 提交于 2020-01-14 06:42:13

问题


What I am trying to do is replace a url and pattern e.g. ###http://www.google.com### with the link wrapped by a <a> tag e.g. <a href="http://www.google.com">Go There</a>

The problem I face is that this url and pattern can appear anywhere in my webpage and It's containing element is always different - here is what I've done.

$('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>'));
  }

});

This works http://jsfiddle.net/84T9u/ but I feel that it is slightly inefficient as it has to iterate over every element in the <body> and there could be hundreds of these link patterns across each page of my site.

I have started to look at using the :contains() selector, I have found some answers on SO that extend this method to allow the use of regex, however I don't know enough about how the :contains() method works. Would it be any more efficient, or is it very similar in functionality to the .each() that I am using - iterating over all elements to find the desired text or pattern?


回答1:


You can use the following code :

$('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>"));

  }

});

OR Simply :

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



回答2:


Don't iterate or use any heavy XML methods, just change the HTML as a string:

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


来源:https://stackoverflow.com/questions/21017744/efficient-find-and-replace-pattern-in-body-text-using-regular-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!