0

I'm trying to check if there is a value between 'mystring' and the end character (which is a pipe). But

new RegExp('mystring:.+\|').test('bla')

Evaluates to true, even though I am escaping the '|' operator. What I was trying to achieve was this:

new RegExp('mystring:.+\|').test('mystring:|')

Evaluate to False (as nothing between 'mystring:' and the escaped '|'.

new RegExp('mystring:.+\|').test('mystring:something|')

Evaluate to True.

This isn't the behvaior I'm seeing as everything is evaluating to True and it doesn't look like the '|' is being escaped...

  • See [Why do regex constructors need to be double escaped?](http://stackoverflow.com/questions/17863066/why-do-regex-constructors-need-to-be-double-escaped) (which is close to being a duplicate of this question, but it assumes knowledge of the solution here already). Your `\|` expression is first being escaped according to the rules of string literal escape sequences. Check the value of the expression `"\|"` in your console: it's `"|"`. – apsillers Aug 12 '15 at 19:28
  • This is why you should use regex literals. – SLaks Aug 12 '15 at 19:28

1 Answers1

1

Escape the backslash. If " is used inside RegExp constructor then you must escape all the backslashes present inside the regex one more time.

new RegExp('mystring:.+\\|').test('mystring:something|')

or

new RegExp('mystring:.+[|]').test('mystring:something|')
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274