Tuesday 25 April 2017

regex - How do I split a string with multiple separators in javascript?



How do I split a string with multiple separators in JavaScript? I'm trying to split on both commas and spaces but, AFAIK, JS's split function only supports one separator.


Answer



Pass in a regexp as the parameter:




js> "Hello awesome, world!".split(/[\s,]+/)
Hello,awesome,world!


Edited to add:



You can get the last element by selecting the length of the array minus 1:



>>> bits = "Hello awesome, world!".split(/[\s,]+/)
["Hello", "awesome", "world!"]

>>> bit = bits[bits.length - 1]
"world!"


... and if the pattern doesn't match:



>>> bits = "Hello awesome, world!".split(/foo/)
["Hello awesome, world!"]
>>> bits[bits.length - 1]
"Hello awesome, world!"


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...