不区分大小写的单词在一个范围内包装它

时间:2015-08-14 13:49:12

标签: javascript jquery search replace case-insensitive

我制作了一个小脚本,旨在找到一个字符串并将其包装在一个范围内。该字符串存储在变量中。

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

换句话说,我希望找到并强调不区分大小写的

谢谢!

4 个答案:

答案 0 :(得分:2)

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>

答案 1 :(得分:2)

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

&#13;
&#13;
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>'))
    }
  })
});
&#13;
.highlight {
  background: red
}
&#13;
<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>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

创建一个带有大小写密集标志的正则表达式,并在回调中捕获值以替换正确的大小写等

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

答案 3 :(得分:0)

这是用于保持您要替换的内容大写的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);
});