0

I'm looking to replace string with variable in regex.

re = new RegExp(/(?:^|\b)(asd)(?=\b|$)/, 'g')

After i get re i replace it and it works but this is limited to asd string.

How can i put variable d in place of asd string? I tried following:

re = new RegExp('(?:^|\b)(' + d + ')(?=\b|$)', 'g')

But it didn't work, any help is appreciated. (I'm Using CoffeeScript)

Mil
  • 59
  • 8
  • Sure, you did not define *word boundary* with `"\b"`, but a backspace char. You need to use `"\\b"`. Just use `re = new RegExp('\\b' + d + '\\b', 'g')`. If you have special chars in `d`, you will come across a different issue though. – Wiktor Stribiżew Mar 01 '17 at 09:50
  • Thank you, i escaped "\b" and it works now: re = new RegExp('(?:^|\\b)('+d+')(?=\\b|$)', 'g') – Mil Mar 01 '17 at 10:01
  • @WiktorStribiżew i may have special chars in variable, is there a way to escape them? Thanks Wiktor – Mil Mar 02 '17 at 15:21
  • 1
    Yes, see http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript – Wiktor Stribiżew Mar 02 '17 at 16:09

0 Answers0