Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex split groups of digits and non-digits not working in Javascript

I've a simple regex pattern that should split groups of digits and non-digits. so a string like 12AB34CD should become an array like ["12", "AB", "34", "CD"] when I use this (http://gskinner.com/RegExr/) tool to test the expression it works fine but it doesn't seem to work in Javascript

var code = "12AB34CD";
var regex =  new RegExp(/\d+|\D+/g);
var codeArray = code.split(regex);
console.log(codeArray);

this will result in an array but all empty strings ["", "", "", "", ""]
What am I missing here?

like image 592
busyBee Avatar asked Jan 19 '26 10:01

busyBee


2 Answers

You can use match:

code.match(/\d+|\D+/g); //=> ["12", "AB", "34", "CD"]
like image 152
elclanrs Avatar answered Jan 20 '26 22:01

elclanrs


JavaScript's regex split() doesn't include the separators (the things that matched the regex) - only the things that were in between the separators. That's why you get 5 empty strings - because there are 4 matches for your regex, and around those 4 matches are no other characters.

"" "12" "" "AB" "" "34" "" "CD" ""

    ^       ^       ^       ^
    |       |       |       |
    +-------+-------+-------+--- regex (separator) matches

Instead, since you actually want the things that match the regex, and not the ones in between, you should just use .match() instead of .split(), which will give you back all of your matches.

like image 43
Amber Avatar answered Jan 21 '26 00:01

Amber



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!