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

So, I'm trying to write a regex that matches all numbers. Here is that regex:

/\b[\d \.]+\b/g

And I try to use it on the string:

100 two 100

And everything works fine; it matches both of the numbers.

But I want to rewrite the regex in the form:

new RegExp(pattern,modifiers)

Because I think it looks clearer. So I write it like this:

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

But now it won't match the former test string. I have tried everything, but I just can't get it to work. What am I doing wrong?

Answers:

Answer

Please ignore my close vote. 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/

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.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.