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
function filter(searchTerm) {
var searchPattern = new RegExp('('+searchTerm+')', 'ig');
....
textToCheck = textToCheck.replace(searchPattern, '<span class="searchMatchTitle">$1</span>');
...
}
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With