Reputation: 23
I have a string that I want to split by digit. The problem is the separator should be kept in the results array.
'A1B2C'.split(/\d/);
// ['A', 'B', 'C']
I'm getting letters only while I expect digits too, something like ['A', '1', 'B', '2', 'C']
.
Upvotes: 2
Views: 49
Reputation: 780843
Putting a capture group around the regexp tells split()
to keep the delimiters in the result.
console.log('A1B2C'.split(/(\d+)/));
Note that if the string begins or ends with a digit, this will result in an extra empty element before/after it:
console.log('5A1B2C6'.split(/(\d+)/));
If this is a problem, you can filter them out.
console.log('5A1B2C6'.split(/(\d+)/).filter(s => s != ""));
Upvotes: 4
Reputation: 386560
You could use String#match
instead and take connected same items.
console.log('A1BB222C'.match(/\D+|\d+/g));
Upvotes: 1