我想在[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]);
但是,我得到的结果是:
h]Bm[/ch] Time flies by when[ch]A[/ch] the night is young[ch]C[/c
如何在数组中存储每个字符串? 我想要的结果是
chords = ["Bm","A","C"]
答案 0 :(得分:2)
您当前模式的问题很小但很棘手:
\[ch\](.*)\[/ch\]
.*
数量将在[ch]
和[/ch]
之间消耗尽可能多的数量。这意味着您将始终只在这里获得一场比赛:
Time flies by when[ch]A[/ch] the night is young
要获得每个匹配对,请使点延迟,即使用(.*?)
。请考虑以下代码:
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);
答案 1 :(得分:1)
您可以使用此正则表达式/\[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);
答案 2 :(得分:0)
尝试split
和filter
test.split(/\[ch\]|\[\/ch\]/).filter( (s,i ) => i % 2 == 1 )
<强>演示强>
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);
<强>解释强>
Split
[ch]
或[/ch]
filter
- 在偶数索引。