匹配每一个字符

时间:2013-04-12 14:55:17

标签: javascript regex

如何将字符串中的每个第二个字符与正则表达式匹配:

'abcdef'.match(???) => ['a', 'c', 'e']

我有这种非正则表达式解决方案:

spl = []; for(var i = 0; i < str.length; i += 2) spl.push(str.charAt(i));

但寻找更优雅的东西。

4 个答案:

答案 0 :(得分:7)

另一种可能的方法:

'abcdefg'.replace(/.(.)?/g, '$1').split('');

它不需要任何垫片。

答案 1 :(得分:5)

您也可以在没有正则表达式的情况下执行此操作。

'abcdef'.split("").filter(function(v, i){ return i % 2 === 0; });

如果IE&lt; = 8支持是一个问题,您可以添加this polyfill


另一个解决方案,更详细,但性能更好,不需要垫片:

var str = "abcdef", output = [];
for (var i = 0, l = str.length; i < l; i += 2) {
    output.push(str.charAt(i));
}

JSPerf

答案 2 :(得分:3)

您可以使用..?ES5 map function(可以通过垫片为尚未拥有它的浏览器提供):

"abcde".match(/..?/g).map(function(value) { return value.charAt(0); });
// ["a", "c", "e"]

答案 3 :(得分:2)

使用Array.prototype.map也是一个选项:

var oddChars = Array.prototype.map.call('abcdef', function(i,k)
{
    if (k%2===0)
    {
        return i;
    }
}).filter(function(x)
{
    return x;
    //or if falsy values are an option:
    return !(x === undefined);
});

oddChars现在是["a","c","e"] ...