文字列内のすべての文字を正規表現と一致させるにはどうすればよいですか:
'abcdef'.match(???) => ['a', 'c', 'e']
私はこの非正規表現ソリューションを持っています:
spl = []; for(var i = 0; i < str.length; i += 2) spl.push(str.charAt(i));
しかし、よりエレガントなものを探しています。
文字列内のすべての文字を正規表現と一致させるにはどうすればよいですか:
'abcdef'.match(???) => ['a', 'c', 'e']
私はこの非正規表現ソリューションを持っています:
spl = []; for(var i = 0; i < str.length; i += 2) spl.push(str.charAt(i));
しかし、よりエレガントなものを探しています。
別の可能なアプローチ:
'abcdefg'.replace(/.(.)?/g, '$1').split('');
シムは必要ありません。
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));
}
使用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"]
...