Skip to content
Advertisement

Javascript – How to extract text with regex

I am new to Regexes. Now I need to write one to suit my needs. I have this string:

1 [00:00:12.00 – 00:01:20.00] Hello there – I’ve come to help you.

I would somehow need to bring it to this form:

const extracted = [
"1",
"[00:00:12.00 - 00:01:20.00]",
"Hello there - I've come to help you."
]

I have tried with this approach:

const testSubject = "1 [00:00:12.00 - 00:01:20.00] Hello there - I've come to help you."
let result = testSubject.match(/$[^$]++$/)

But I am getting this error:

Invalid regular expression: /$[^$]++$/: Nothing to repeat

I have used this place to get the pattern: http://regex.inginf.units.it/

Advertisement

Answer

As already pointed out by anubhava, possessive quantifiers ++ are not supported in Javascript. You can see the error message in this demo when selecting Javascript at the left panel.

There is no $ in the string, but if you want to use a negated character class not matching the brackets, you might use a negated character class with a capture group and use split.

const pattern = /s*([[^][]+])s*/;
const s = "1 [00:00:12.00 - 00:01:20.00] Hello there - I've come to help you.";
console.log(s.split(pattern))
Advertisement