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

标签 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('');
}

这显然只是返回句子。我需要在标签内包含数值。有什么办法可以做到这一点吗?

最佳答案

我建议:

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 .

引用文献:

关于javascript - 如何获得 Javascript 正则表达式匹配的字符串的实际值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17173868/

相关文章:

javascript - Google 登录按钮未在 React 中呈现

python正则表达式,剪切多行

php:在空白处将字符串分成两半,直到结果部分都不长于 x 个单词

javascript - html中的多级列表

javascript - 使用 web3 ethereum 调用智能合约方法

javascript - onchange 日期输入

regex - 使用正则表达式验证 Youtube 播放列表 URL

javascript - 在 Javascript 中,获取匹配正则表达式的长度

android - 如何获取word中的特殊字符及其点击事件

ruby - 拆分开始和结束时的空字符串