Reputation: 41
I had a question regarding splitting alphanumeric characters. Say I have an array that looks like the following:
var arr = ["Z100X", "RT540X", "3001X", "YRT560X"];
How do I split the characters in this array so that the array ends up like this:
var arr = ["Z", "100X", "RT", "540X", "3001X", "YRT", "560X"]
I was thinking about using a general expression like this
arr.replace(/[\d]+/, ","+/[\d]+/);
But not sure how to keep the "X" character at the end attached to the number.
Any help would be greatly appreciated! Thanks.
Upvotes: 1
Views: 950
Reputation: 42
var arr = ["Z100X", "RT540X", "3001X", "YRT560X"];
var res = arr.toString().match(/[A-Z]+|\d+[A-Z]/g);
console.log(res);
Upvotes: 1
Reputation: 26161
You may also do as follows;
var arr = ["Z100X", "RT540X", "3001X", "YRT560X"],
result = arr.reduce((r,s) => r.concat(s.match(/[A-Z]+|\w+/g)),[]);
console.log(result);
Upvotes: 1
Reputation: 1
You can use .toString()
, .match()
with RegExp
/[A-Z]+|\d+[A-Z]+/g
to match one or more A-Z or one or more digits followed by one or more A-Z.
The RegExp
is intended to match for example "Z"
or "RT"
or "YRT"
: [A-Z]+
, or, "100X"
or "3001X"
: \d+[A-Z]+
; the g
flag is for purpose of returning all matches found.
var arr = ["Z100X", "RT540X", "3001X", "YRT560X"];
var res = arr.toString().match(/[A-Z]+|\d+[A-Z]+/g);
console.log(res);
Upvotes: 4
Reputation: 25634
You can use .split()
with a regex matching [a bunch of letters] followed by [any non-empty String]:
var arr = ["Z100X", "RT540X", "3001X", "YRT560X"],
arr2 = [];
for(var i=0, l=arr.length; i<l; i++) {
var parts = arr[i].split(/([A-Z]+)(.+)/).filter(Boolean);
arr2.push.apply(arr2, parts);
}
console.log(arr2);
Here, .filter(Boolean)
is used to remove empty Strings from the Array.
Upvotes: 1