0

I'm trying to match the phrase "/$" using the RegExp constructor, but no amount of escaping seems to help. Am is missing something?

RegExp("\/\$").test("/$")
// false
RegExp("/$").test("/$")
// false
RegExp("\/$").test("/$")
// false
RegExp("/\$").test("/$")
// false
silverwind
  • 3,296
  • 29
  • 31

1 Answers1

2

You need to use \\ instead of \ and there is no need to escape / or use regex /\/\$/ directly. Check RegExp documentation for more info.

When using the constructor function, the normal string escape rules (preceding special characters with \ when included in a string) are necessary.

For example, /\w+/ is equivalent to new RegExp('\\w+')

console.log(
  RegExp("/\\$").test("/$")
)

//or

console.log(
  /\/\$/.test("/$")
)

Refer : Javascript regular expression - string to RegEx object

Community
  • 1
  • 1
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188