How to split JavaScript string into space or comma?

If i try

"my, tags are, in here".split(" ,") 

I get the following

 [ 'my, tags are, in here' ] 

While i want

 ['my', 'tags', 'are', 'in', 'here'] 
+76
javascript
Apr 27 2018-12-12T00:
source share
6 answers

String.split can also take a regular expression:

 input.split(/[ ,]+/); 

This particular regular expression is split into a sequence of one or more commas or spaces, so, for example, several consecutive spaces or a comma sequence + space do not produce empty elements in the results.

+148
Apr 27 2018-12-12T00:
source share

Using .split(/[ ,]+/) recommended, but with natural sentences, sooner or later you will get empty elements in the array. for example ['foo', '', 'bar'] .

This is normal if appropriate for your use case. But if you want to get rid of empty elements, you can do:

 var str = 'whatever your text is...'; str.split(/[ ,]+/).filter(Boolean); 
+25
May 19 '14 at 2:08
source share
 "my, tags are, in here".split(/[ ,]+/) 

result:

 ["my", "tags", "are", "in", "here"] 
+11
Apr 27 2018-12-12T00:
source share

you can use regex to catch any space length and it will look like this:

  var text = "hoi how are you"; var arr = text.split(/\s+/); console.log(arr) will result : ["hoi", "how", "are", "you"] console.log(arr[2]) will result : "are" 
+10
Sep 22 '15 at
source share

input.split(/\s*[\s,]\s*/)

... \s* matches zero or more space characters (not just spaces, but also tabs and newlines).

... [\s,] matches one space character or one comma

If you want to avoid empty input elements like "foo,bar,,foobar" , this will do the trick:

input.split(/(\s*,?\s*)+/)

+ matches one or more of the preceding character or group.

Edit:

Added ? after a comma that matches zero or one comma.

Edit 2:

Turns off edit 1 was an error. I fixed it. Now for the expression you need to have at least one comma or one space.

+3
Apr 27 '12 at 7:50
source share

When I want to take into account additional characters, such as commas (in my case, each token can be entered with quotes), I would do string.replace () to change the other delimiters into spaces, and then split into spaces.

0
Jun 21 '13 at 22:37
source share



All Articles