Regex created via new RegExp(myString) not working (backslashes)

Your problem is that the backslash in a string has a special meaning; if you want a backslash in your regexp, you first need to get literal backslashes in the string passed to the regex:

new RegExp('\\b[\\d \\.]+\\b','g');

Note that this is a pretty bad (permissive) regex, as it will match ". . . " as a ‘number’, or "1 1...3 42". Better might be:

/-?\d+(?:\.\d+)?\b/

enter image description here

Note that this matches odd things like 0000.3 also does not match:

  • Leading +
  • Scientific notation, e.g. 1.3e7
  • Missing leading digit, e.g. .4

Also, note that using the RegExp constructor is (marginally) slower and certainly less idiomatic than using a RegExp literal. Using it is only a good idea when you need to constructor your RegExp from supplied strings. Most anyone with more than passing familiarity with JavaScript will find the /.../ notation fully clear.

Leave a Comment