3

文字列内のすべての文字を正規表現と一致させるにはどうすればよいですか:

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

私はこの非正規表現ソリューションを持っています:

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

しかし、よりエレガントなものを探しています。

4

4 に答える 4

7

別の可能なアプローチ:

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

シムは必要ありません。

于 2013-04-12T15:02:52.893 に答える
5

You can do this without regex as well.

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

If IE<=8 support is an issue, you may add this polyfill.


Another solution, more verbose but with better performance which doesn't require shims:

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

JSPerf

于 2013-04-12T14:58:46.560 に答える
3

ES5関数..?を使用できます(これは、まだネイティブに実装されていないブラウザー用に shim によって提供できます)。map

"abcde".match(/..?/g).map(function(value) { return value.charAt(0); });
// ["a", "c", "e"]
于 2013-04-12T14:57:46.040 に答える
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"]...

于 2013-04-12T15:07:35.773 に答える