Positive look behind in JavaScript regular expression

Viewed 52675

I've a document from which I need to extract some data. Document contain strings like these

Text:"How secure is my information?"

I need to extract text which is in double quotes after the literal Text:

How secure is my information?

How do I do this with regex in Javascript

8 Answers

Here is an example showing how you can approach this.

1) Given this input string:

const inputText = 
`Text:"How secure is my information?"someRandomTextHere
Voice:"Not very much"
Text:"How to improve this?"
Voice:"Don't use '123456' for your password"
Text:"OK just like in the "Hackers" movie."`;

2) Extract data in double quotes after the literal Text: so that the results is an array with all matches like so:

["How secure is my information?",
 "How to improve this?",
 "OK just like in the \"Hackers\" movie."]

SOLUTION

function getText(text) {
  return text
    .match(/Text:".*"/g)
    .map(item => item.match(/^Text:"(.*)"/)[1]);
}

console.log(JSON.stringify(    getText(inputText)    ));

RUN SNIPPET TO SEE A WORKING DEMO

const inputText = 
`Text:"How secure is my information?"someRandomTextHere
Voice:"Not very much"
Text:"How to improve this?"
Voice:"Don't use '123456' for your password"
Text:"OK just like in the "Hackers" movie."`;



function getText(text) {
  return text
    .match(/Text:".*"/g)
    .map(item => item.match(/^Text:"(.*)"/)[1]);
}

console.log(JSON.stringify(    getText(inputText)    ));

If you, like me, get here while researching a bug related to the Cloudinary gem, you may find this useful:

Cloudinary recently released version 1.16.0 of their gem. In Safari, this crashes with the error 'Invalid regular expression: invalid group specifier name'.

A bug report has been filed. In the meantime I reverted to 1.15.0 and the error went away.

Hope this saves someone some lifetime.

Related