Reputation: 419
var string;
var splitstring = string.split("????");
my string is 12BLG123 i need the array splitstring to have elements 12,BLG,123 (The alphabets and numbers randomly vary)
Upvotes: 0
Views: 71
Reputation: 1955
const string = `12BLG123`
const splitString = string.split(/(\d+)/).filter(i => i)
console.log(splitString)
The regex splits the string by numeric strings. Since split doesn't include the value that it is being split by, we use the capturing syntax to include the numeric strings. Empty strings are introduced if the string starts or ends with numeric strings so we use filter(i => i)
to remove the empty strings (it works because empty strings are falsey values in javascript).
Upvotes: 4
Reputation: 2610
Though not regex or split, but you can do something like this,
var str = "12BLG123";
var result = [].reduce.call(str, (acc, a) => {
if (!acc.length) return [a]; // initial case
let last = acc[acc.length - 1];
// same type (digit or char)
if (isNaN(parseInt(a, 10)) == isNaN(parseInt(last.charAt(0), 10)))
acc[acc.length - 1] = last + a;
// different type
else acc.push(a);
// return the accumulative
return acc;
}, [] /* the seed */);
console.log(result);
Upvotes: 2
Reputation: 226
This regex will probably work.
var splitString = string.split("[^A-Z0-9]+|(?<=[A-Z])(?=[0-9])|(?<=[0-9])(?=[A-Z])");
Upvotes: 0