不区分大小写的查找单词并将其包装在一个跨度中

Case insensitive find word an wrap it in a span

我制作了一个小脚本,旨在查找一个字符串并将其包装在一个跨度中。字符串存储在变量中。

HTML

 <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>

jQuery

var term = "friend";
var item = $("h2");
$(item).each(function() {
  var itemHTML = $(this).html();
  var newItemHTML = itemHTML.replace(term, '<span class="highlight">' + term + '</span>'); 
  $(this).html(newItemHTML);
});

这里是全部内容:http://jsfiddle.net/97hxbyy0/

脚本成功将friend替换为friend;但我希望它也用 friend.

替换 FriendFRIEND

换句话说,我希望找到并突出显示 不区分大小写

谢谢!

使用带有 i 选项的不区分大小写的正则表达式

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>

创建一个设置了不区分大小写标志的正则表达式,并捕获回调中的值以替换为正确的大小写等

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

这里是 javascript 以保留您要替换的内容的大写。

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);
});

我认为更安全的选择是这样做,因为您不想更改锚元素的内容

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"></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>