如何获得Javascript正则表达式匹配的字符串的实际值?

时间:2013-06-18 16:10:53

标签: javascript regex split

我正在尝试编写一个Javascript函数,它将带有<0>的字符串(其中0可以是任何数字)并删除它并获取其中数字的实际值。例如,如果给出这句话:

'By now you\'re probably familiar with <0>X, a drawing application that has won an <1>Awards and plenty of attention for its user interface, which has rethought the way basic interactions like <2>pinch-to-zoom or <3>color selection should work on a touchscreen.'

我希望它能给我这个字符串:

'By now you\'re probably familiar with X, a drawing application that has won an Awards and plenty of attention for its user interface, which has rethought the way basic interactions like pinch-to-zoom or color selection should work on a touchscreen.'

和这个数组:

[0, 1, 2, 3]

目前我有这个:

function(sentence) {
  return sentence.split(/\<[0-9]+\>/).join('');
}

显然只是返回句子。我需要在标签内部有数字值。有没有办法做到这一点?

1 个答案:

答案 0 :(得分:2)

我建议:

function regexAndArray (str) {
    var reg = /(<(\d+)>)/g,
        results = {
            string : '',
            stripped : []
        };
    results.string = str.replace(reg, function(a,b,c){
        results.stripped.push(c);
        return '';
    });
    return results;
}

console.log(regexAndArray('By now you\'re probably familiar with <0>X, a drawing application that has won an <1>Awards and plenty of attention for its user interface, which has rethought the way basic interactions like <2>pinch-to-zoom or <3>color selection should work on a touchscreen.'));

JS Fiddle demo

参考文献: