I have this code:
var r = /(?:^\s*([^\s]*)\s*)(?:,\s*([^\s]*)\s*){0,}$/ var s = " a , b , c " var m = s.match(r) m => [" a , b , c ", "a", "c"]
Looks like the whole string has been matched, but where has "b"
gone? I would rather expect to get:
[" a , b , c ", "a", "b", "c"]
so that I can do m.shift()
with a result like s.split(',')
but also with whitespaces removed.
Do I have a mistake in the regexp or do I misunderstand String.prototype.match
?
To split the sentences by comma, use split(). For removing surrounding spaces, use trim().
To split a string by space or comma, pass the following regular expression to the split() method - /[, ]+/ . The method will split the string on each occurrence of a space or comma and return an array containing the substrings.
JavaScript String trim()The trim() method removes whitespace from both sides of a string. The trim() method does not change the original string.
Here's a pretty simple & straightforward way to do this without needing a complex regular expression.
var str = " a , b , c " var arr = str.split(",").map(function(item) { return item.trim(); }); //arr = ["a", "b", "c"]
The native .map
is supported on IE9 and up: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
Or in ES6+ it gets even shorter:
var arr = str.split(",").map(item => item.trim());
And for completion, here it is in Typescript with typing information
var arr: string[] = str.split(",").map((item: string) => item.trim());
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