4

I want to use this function but preserving the uppercase or lowercase so for example having something like

var value = 'Replace a string';

var search = 'replace';

value.replace(search, "<span style='font-weight: bold'>"+search+'<span>');

And the output of value be:

Replace a string

Jerome Ansia
  • 6,854
  • 11
  • 53
  • 99
  • This should be the correct answer: [value = value.replace(new RegExp(search,"gi"), '...$&...');](https://stackoverflow.com/a/19252324/2816279) – Pedro Ferreira Dec 13 '17 at 23:47

2 Answers2

8

Since you're leaving the word itself as-is, you can use a simple regex:

var value = 'Replace a string';
var search = /replace/i;
value = value.replace(search, "<span style='font-weight: bold'>$&</span>");

The $& indicates the matched pattern.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • Thanks a lot it's working i still have to wait a few minutes and i'll accept yours. I just have a little issue left replace it's in fact a var so how i do this: var search = /'+my_var+'/i; (this is not working) – Jerome Ansia May 15 '12 at 19:45
  • got it: http://stackoverflow.com/questions/494035/how-do-you-pass-a-variable-to-a-regular-expression-javascript :D perfect thanks again – Jerome Ansia May 15 '12 at 19:47
7

Make search a regular expression and catch the case insensitive "replace" in a group:

var search = /(replace)/i;

Then, replace the word with the group, inside your <span> tag:

value.replace(search, '<span style="font-weight: bold">$1<span>');
rid
  • 61,078
  • 31
  • 152
  • 193