-1

I want to get every string between [ch] and [/ch]

var test = "[ch]Bm[/ch] Time flies by when[ch]A[/ch] the night is young[ch]C[/ch]"
var testRE = test.match("\[ch\](.*)\[/ch\]"); alert(testRE[1]);

But, the result I get is:

h]Bm[/ch] Time flies by when[ch]A[/ch] the night is young[ch]C[/c

How to store every string inside an array? My desired result is become

chords = ["Bm","A","C"]
elcortegano
  • 2,444
  • 11
  • 40
  • 58
calvin sugianto
  • 610
  • 7
  • 27
  • i'm sorry, why you downvote my question? @wiktor-stribiżew I have search for similar question and didn't found any. When i see this question, it seems different from my case https://stackoverflow.com/questions/22444/my-regex-is-matching-too-much-how-do-i-make-it-stop – calvin sugianto Feb 21 '18 at 11:01
  • There are too many identical questions. Posting and answering this one is not necessary, it has been answered many times. 2 more links added. + 677 and 25 upvotes for the same answers. – Wiktor Stribiżew Feb 21 '18 at 11:03

3 Answers3

2

The problem with your current pattern is a minor but tricky one:

\[ch\](.*)\[/ch\]

The .* quantity will consume as much as possible between [ch] and [/ch]. This means that you will always just get one match here:

Time flies by when[ch]A[/ch] the night is young

To get each matching pair, make the dot lazy, i.e. use (.*?). Consider this code:

var test = "[ch]Bm[/ch] Time flies by when[ch]A[/ch] the night is young[ch]C[/ch]"
var regex = /\[ch\](.*?)\[\/ch\]/g
var matches = [];
var match = regex.exec(test);
while (match != null) {
    matches.push(match[1]);
    match = regex.exec(test);
}
console.log(matches);
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
1

You can use this regex /\[ch\](.*?)\[\/ch\]/g

var test = "[ch]Bm[/ch] Time flies by when[ch]A[/ch] the night is young[ch]C[/ch]"
var regex = /\[ch\](.*?)\[\/ch\]/g;
var testRE = [];
var match;
while (match = regex.exec(test)) {
    testRE.push(match[1]);
}
console.log(testRE);
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51
0

Try split and filter

test.split(/\[ch\]|\[\/ch\]/).filter( (s,i ) => i % 2 == 1 )

Demo

var test = "[ch]Bm[/ch] Time flies by when[ch]A[/ch] the night is young[ch]C[/ch]"
var output = test.split(/\[ch\]|\[\/ch\]/).filter((s, i) => i % 2 == 1);

console.log(output);

Explanation

  • Split by either [ch] or [/ch]
  • filter-in even indices.
gurvinder372
  • 66,980
  • 10
  • 72
  • 94