本文介绍了不区分大小写的单词将其环绕起来的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have made a small script designed to find a string and wrap it in a span. The string is stored in a variable.

 <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 替换 Friend FRIEND .

The script successfully replaces friend with friend; but I want it to also replace Friend or FRIEND with friend.

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

In other words, I wish to make that find and highlight case insensitive.

谢谢!

推荐答案

我认为将是一个更安全的选择,因为您不想更改锚元素的内容

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>

这篇关于不区分大小写的单词将其环绕起来的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 00:28