Prashant Agrawal
Prashant Agrawal

Reputation: 670

What should be the regex to match the start of a string

I have a string something like and I want to match just the first '{' of every {{xxxx}} pattern

{{abcd}}{{efg}}{{hij}}

{{abcd}}{{efg}}{{hij}}{

I tried with /(\s|^|.){/g but this pattern matches

{{abcd}}{{efg}}{{hij}}

Can some one guide me in the right direction

Upvotes: 0

Views: 59

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626689

You need to use /(^|[^{]){/g (that matches and captures into Group 1 start-of-string or any char other than {, and then matches a {) and check if Group 1 matched at each RegExp#exec iteration. Then, if Group 1 matched, increment the match index:

var re = /(^|[^{]){/g;
var str = "{{abcd}}{{efg}}{{hij}}\n{{abcd}}{{efg}}{{hij}}{";
//         0       8      15       23      31     38     45
var m, indices = [];
while ((m = re.exec(str)) !== null) {
    indices.push(m.index + (m[1] ? 1 : 0));
}
console.log(indices);

Upvotes: 1

Related Questions