Case insensitive find word an wrap it in a span

北城余情 提交于 2019-11-29 17:42:47

I think a safer option will be is to do, because you don't want to change the contents of the anchor element

if (!RegExp.escape) {
  RegExp.escape = function(value) {
    return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&")
  };
}

var term = "friend";
var regex = new RegExp('(' + RegExp.escape(term) + ')', 'ig');
var item = $("h2");
$(item).each(function() {

  $(this).contents().each(function() {
    if (this.nodeType == Node.TEXT_NODE && regex.test(this.nodeValue)) {
      $(this).replaceWith(this.nodeValue.replace(regex, '<span class="highlight">$1</span>'))
    }
  })
});
.highlight {
  background: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h2>I have a lot of friends.</h2>
<h2>My best friend's name is Mike.</h2>
<h2>My best Friend's website is <a href="http://www.myfriendmike.com">myfriendmike.com</a>.</h2>
<h2><a href="http://www.myfriendmike.com">myfriendmike.com</a> is my Friend's website.</h2>

Use a case-insensitive regex with the i option

var term = /friend/i;

var term = /friend/i;
var replaceWith = "friend";
var item = $("h2");
$(item).each(function() {
   var itemHTML = $(this).html();
   var newItemHTML = itemHTML.replace(term, '<span class="highlight">' + replaceWith + '</span>'); 
    $(this).html(newItemHTML);
});
.highlight { background: red}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h2>I have a lot of friends.</h2>
<h2>My best Friend's name is Mike.</h2>
<h2>My best FRIEND's website is <a href="http://www.myfriendmike.com">myfriendmike.com</a>.</h2>

Create a regex with the case-insensive flag set, and capture the value in a callback to replace with the correct case etc

var term = "friend";
var item = $("h2");
var reg  = new RegExp(term, "i");

item.html(function (i, html) {
    return html.replace(reg, function (match) {
        return '<span class="highlight">' + match + '</span>'
    });
});

FIDDLE

Here is the javascript to keep the capitalization of what you are replacing.

var term = /friend/i;
var item = $("h2");
$(item).each(function() {
   var itemHTML = $(this).html();
   var newItemHTML = itemHTML.replace(term, '<span class="highlight">$&</span>'); 
    $(this).html(newItemHTML);
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!