DD Ariamia
DD Ariamia

Reputation: 23

Split by digit and keep that digit in the results

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

Answers (3)

Barmar
Barmar

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

Nina Scholz
Nina Scholz

Reputation: 386560

You could use String#match instead and take connected same items.

console.log('A1BB222C'.match(/\D+|\d+/g));

Upvotes: 1

samnu pel
samnu pel

Reputation: 914

You just need to use split. This should work

"a1b2c3".split('');

Upvotes: 0

Related Questions