Search code examples
javascriptjquerysearchreplacecase-insensitive

Case insensitive find word an wrap it in a span


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

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

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

Here is the entire thing put together: http://jsfiddle.net/97hxbyy0/

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.

Thank you!


Solution

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