Yoshi Walsh
Yoshi Walsh

Reputation: 2077

JavaScript RegEx not matching [

I'm making a .LRC file parser for JavaScript and I've hit a snag. I have the following code:

var getTimecodes = new RegExp("\[[0-9]{2}:[0-9]{2}\.[0-9]{2}\]", "g");
var testLine = "[00:25.03][00:38.86][03:36.98][03:50.64]but man you should've seen him";
var timecodes = testLine.match(getTimecodes);
var lineText = testLine.replace(getTimecodes, "");

console.log(timecodes);
console.log(lineText);

which according to my understanding of RegEx and several different RegEx testing sites, including one written entirely in JavaScript, I should be getting the following results:

["[00:25.03]", "[00:38.86]", "[03:36.98]", "[03:50.64]"]

but man you should've seen him

Instead I am getting the following output:

["00:25.03]", "00:38.86]", "03:36.98]", "03:50.64]"]

[[[[but man you should've seen him

Could anyone shed some light on this please? I've probably done something dumb but I just can't work out what it is...

Thanks, YM

Upvotes: 3

Views: 61

Answers (1)

anubhava
anubhava

Reputation: 785491

Use double \\ in RegExp constructor:

var getTimecodes = new RegExp("\\[[0-9]{2}:[0-9]{2}\\.[0-9]{2}\\]", "g");

OR simply:

var getTimecodes = /\[[0-9]{2}:[0-9]{2}\.[0-9]{2}\]/g;

Reason: Since RegExp constructor takes a String therefore String needs one escaping and regex engines needs second escaping.

Upvotes: 5

Related Questions