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?
You can use match:
code.match(/\d+|\D+/g); //=> ["12", "AB", "34", "CD"]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With