Positive look behind in JavaScript regular expression

I just want to add something: JavaScript doesn't support lookbehinds like (?<= ) or (?<! ).

But it does support lookaheads like (?= ) or (?! ).


You can just do:

/Text:"(.*?)"/

Explanation:

  • Text:" : To be matched literally
  • .*? : To match anything in non-greedy way
  • () : To capture the match
  • " : To match a literal "
  • / / : delimiters

Lookbehind assertions were recently finalised for JavaScript and will be in the next publication of the ECMA-262 specification. They are supported in Chrome 66 (Opera 53), but no other major browsers at the time of writing (caniuse).

var str = 'Text:"How secure is my information?"',
    reg = /(?<=Text:")[^"]+(?=")/;

str.match(reg)[0];
// -> How secure is my information?

Older browsers do not support lookbehind in JavaScript regular expression. You have to use capturing parenthesis for expressions like this one instead:

var str = 'Text:"How secure is my information?"',
    reg = /Text:"([^"]+)"/;

str.match(reg)[1];
// -> How secure is my information?

This will not cover all the lookbehind assertion use cases, however.