Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Case insensitive search with case sensitive replace

I have a simple regex search and replace function and was wondering if there is a good way to go a case sensitive replace on a case insensitive search? Example below:

function filter(searchTerm) {
    var searchPattern = new RegExp(searchTerm, 'ig');
    ....
    textToCheck = textToCheck.replace(searchPattern, '<span class="searchMatchTitle">' + searchTerm + '</span>');

The search term at the top of the function could have a capitol in it and I wanted to make it match any string with upper or lower in it, hence the 'i' flag.

I end up with weird results when doing the replace as it takes the original seach string (which could be any mix) and uses that a replacement where there might be different formatting.

Id really love to preserve the original formatting and add the span around it. Is my approach the best way? If it is, can you use groups in the same way you can in Perl? e.g.

s/ \(=\+\) /\1/g

My attempts using similar types of syntax and examples form the web only result in literal string replace

like image 240
Doug Miller Avatar asked Oct 11 '12 12:10

Doug Miller


2 Answers

function filter(searchTerm) {
    var searchPattern = new RegExp('('+searchTerm+')', 'ig');
    ....
    textToCheck = textToCheck.replace(searchPattern, '<span class="searchMatchTitle">$1</span>');
    ...
}
like image 58
inhan Avatar answered Oct 10 '22 02:10

inhan


You can use groups, but the syntax is slightly different. Try something like this:

var str = 'this is a dog eat Dog eat DOG world'
str = str.replace(/(dog)/gi, '<span>$1</span>')

// str is now: "this is a <span>dog</span> eat <span>Dog</span> eat <span>DOG</span> world"
like image 39
chinabuffet Avatar answered Oct 10 '22 00:10

chinabuffet