' + phrase +...">Geek Answers HandbookSmart linesThis works well for case-insensitive replacements:str = str.replace(new RegExp(phrase, 'gi'), '<span style="color:red;">' + phrase + '</span>'); But I want the case when it was replaced, as indicated above, to not change.+4javascriptAlex polo Aug 9 '10 at 9:29source share2 answersstr = str.replace(new RegExp(phrase, 'gi'), '<span>$&</span>');+1grddev Aug 9 '10 at 9:42source shareGrab the phrase in brackets and use $1 in the replacement string, for example: 'Foobar'.replace(/(foo)/gi, '<x>$1</x>') The result will be <x>Foo</x>bar0reko_t Aug 9 '10 at 9:39source shareMore articles:Is there a most common βiterableβ type adopted by Java for each loop? - javaresponse.setContentType () always trims the space between "; charset"? - javaJava model exception: Java model state [gen [in MyApp] does not exist] after the Eclipse Android Clean project - androidHow can I attach some jQuery to an existing function? - jqueryHow does JUnit find the eclipse plugin under test? - junitMakefile.PL: installing multiple scripts and binaries - perlWhy did my application just use about 36 MB of memory, but am I still getting a low memory warning? - memoryGrouping the same WCF queries - c #How is the JSLint function-inside-loop applied when using jQuery.each ()? - jqueryMemory (and other resources) used by a separate VirtualAlloc distribution - c ++All Articles
This works well for case-insensitive replacements:
str = str.replace(new RegExp(phrase, 'gi'), '<span style="color:red;">' + phrase + '</span>');
But I want the case when it was replaced, as indicated above, to not change.
str = str.replace(new RegExp(phrase, 'gi'), '<span>$&</span>');
Grab the phrase in brackets and use $1 in the replacement string, for example:
$1
'Foobar'.replace(/(foo)/gi, '<x>$1</x>')
The result will be <x>Foo</x>bar
<x>Foo</x>bar