Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split the sentences by ',' and remove surrounding spaces

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?

like image 899
meandre Avatar asked Oct 08 '11 09:10

meandre


People also ask

How do you remove spaces in Split?

To split the sentences by comma, use split(). For removing surrounding spaces, use trim().

How do you split a string with commas and spaces?

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.

How do you trim a space in JavaScript?

JavaScript String trim()The trim() method removes whitespace from both sides of a string. The trim() method does not change the original string.


1 Answers

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()); 
like image 114
FiniteLooper Avatar answered Oct 09 '22 22:10

FiniteLooper