-1

I have this code:

$(this).html(html.replace(/"expedita"/gi, '<strong>$&</strong>'));

which is working but the string to replace is hardcoded, I need to be able to insert a variable

$(this).html(html.replace(/"+search+"/gi, '<strong>$&</strong>'));

search is a variable I have assigned a value I want to replace, but this code is not working, it seems i can't insert a variable into regex expression.

How can I use regex but not have a hardcoded word and be able to use any word?

niko craft
  • 2,893
  • 5
  • 38
  • 67
  • 1
    Possible duplicate of [How do you use a variable in a regular expression?](http://stackoverflow.com/questions/494035/how-do-you-use-a-variable-in-a-regular-expression) – Daniel Bernsons Mar 16 '17 at 22:54
  • 3
    Try `$(this).html(html.replace(new RegExp(search, 'g'), '$&'))`. – kind user Mar 16 '17 at 22:54
  • 1
    @maxit Maybe I should make a full answer, in case of other users have the same problem as you? What do you think? – kind user Mar 17 '17 at 12:03
  • Do not answer duplicates, mark/flag them as duplicates. –  Mar 17 '17 at 22:24

1 Answers1

0

To achieve a flexible and dynamic way to change the replaced expression, use RegExp object.

$(this).html(html.replace(new RegExp(search, 'g'), '<strong>$&</strong>'))

where the search is a variable holding the expression you want to replace.

kind user
  • 40,029
  • 7
  • 67
  • 77