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

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

HTML

I have a lot of friends.

My best friend's name is Mike.

My best friend's website is myfriendmike.com.

jQuery

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

这是整个事情的组合: http : //jsfiddle.net/97hxbyy0/

该脚本成功地将朋友替换为朋友 ; 但我希望它也能和朋友一起取代朋友朋友

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

谢谢!

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

 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, '$1')) } }) }); 
 .highlight { background: red } 
  

I have a lot of friends.

My best friend's name is Mike.

My best Friend's website is myfriendmike.com.

myfriendmike.com is my Friend's website.

使用不区分大小写的正则表达式和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, '' + replaceWith + ''); $(this).html(newItemHTML); }); 
 .highlight { background: red} 
  

I have a lot of friends.

My best Friend's name is Mike.

My best FRIEND's website is myfriendmike.com.

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

 var term = "friend"; var item = $("h2"); var reg = new RegExp(term, "i"); item.html(function (i, html) { return html.replace(reg, function (match) { return '' + match + '' }); }); 

小提琴

这是javascript来保持你要替换的大写字母。

 var term = /friend/i; var item = $("h2"); $(item).each(function() { var itemHTML = $(this).html(); var newItemHTML = itemHTML.replace(term, '$&'); $(this).html(newItemHTML); });