match a string from a text with a Regexp

Viewed 65

I need to get a valid javascript string from text, I tried a lot, but escape characters are bothering me.

Here's code:

Regexp:

const Regexp = /(["']).*?((?<!\\)\1)/;

It does work sometimes

  • text: '$$\''

    expect: '$$\''

  • text: '\\''

    expect: '\\'

    unexpected: '\\''

    Note: Two \ is a valid javascript string, so the ' after \\ is the correct closing quotes.

1 Answers

The bottom line is that strings need to double escape the escape characters. '\\s' becomes '\s' when converting the string before it is fed into the regex processor. And '\\\\' becomes '\\'.

The /regex/ syntax is not a string declaration, so does not need this double escaping.

I suggest you put your regular expression in this site:

https://regex101.com/

The site will syntax highlight the escape sequences for you, and clearly analyze your expression, step by step.

Related