Reputation: 214979
How can I match every second character in a string with a regular expression:
'abcdef'.match(???) => ['a', 'c', 'e']
I have this non-regex solution:
spl = []; for(var i = 0; i < str.length; i += 2) spl.push(str.charAt(i));
but looking for something more elegant.
Upvotes: 3
Views: 4559
Reputation: 70159
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));
}
Upvotes: 5
Reputation: 76405
Using Array.prototype.map
is an option, too:
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
is now ["a","c","e"]
...
Upvotes: 2
Reputation: 106385
Another possible approach:
'abcdefg'.replace(/.(.)?/g, '$1').split('');
It doesn't require any shims.
Upvotes: 7
Reputation: 1074575
You can use ..?
and the ES5 map
function (which can be supplied by a shim for browsers that don't yet have it natively):
"abcde".match(/..?/g).map(function(value) { return value.charAt(0); });
// ["a", "c", "e"]
Upvotes: 3