function getBetween(content, start, end) {
var r = content.split(start);
if (1 in r) {
var z = r[1].split(end);
return z[0];
}
return '';
}
你好,我有以下函数,我写的可以在两个字符串之间得到一个字符串
例如
var string = 'I am 30 years old';
var age = getBetween(string, 'I am ', ' years old');
现在,如果字符串在年龄中出现的次数更多,例如string
I am 30 years old
I am 20 years old
I am 50 years old
Etc等。我想知道是否有办法获得30,20,50和阵列中的其他任何匹配
答案 0 :(得分:1)
您可以使用此功能:
function getBetween(content, start, end) {
var arr = [];
content.replace(new RegExp(start + "(.+)" + end,"g"),function(m,g1){ arr.push(g1); return '';});
return arr;
}
var output = getBetween('I am 30 years old I am 20 years old I am 50 years old', 'I am ', ' years old');
输出:
["30", "20", "50"]
答案 1 :(得分:0)
试试:
function getBetween(content, start, end) {
var result = [];
var r = content.split(start);
for (var i = 1; i < r.length; i++) {
result.push(r[i].split(end)[0]);
}
return result;
}
var output = getBetween('I am 30 years old I am 20 years old I am 50 years old', 'I am ', ' years old');
输出:
["30", "20", "50"]