new RegExp and Strings in JavaScript
When creating a regular expression in JavaScript from a string, the backslashes are consumed1 which can lead to subtle bugs:
new RegExp("\d") // > /d/
new RegExp("\d\w") // > /dw/
There are a couple ways2 to avoid this, using a second backslash //
or using the String.raw
method3:
new RegExp("\\d\\w\\s") // > /\d\w\s/
new RegExp(String.raw`\d\w\s`) // > /\d\w\d/