The main problem is that you are creating a variable that wraps the search query passed in the gap, rather than matching matches. Therefore, when you replace all regular expressions (case insensitive, because "ig") with this wrapped search term, it replaces all instances of this term, regardless of the case with the exact text passed. It is worth noting that this happens with every letter, not just N. Any letter you seek in the form of capital replaces its lowercase copies in the document.
To fix this, instead of replacing 1: 1 ( a.replace('thing','otherthing' ), try passing the function as the second parameter. When you do this, each individual match in the string is passed to that function and replaced with the return value of the function.
For instance:
var a = 'abbacca'; var r = new RegExp('A','ig'); a.replace(r, function(m){ return '_' + m + '_'; });
So instead:
var content = "<span class='match'>" + searchTerm + "</span>"; var replaced = $(selector).text().replace(searchTermRegEx, content);
try the following:
var replaced = $(selector).text().replace(searchTermRegEx, function(m){ return '<span class="match">' + m + '</span>'; });
Here is the fiddle with this change
source share