Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a string by white space or comma?

Tags:

javascript

If I try

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

I get the following

[ 'my, tags are, in here' ] 

Whereas I want

['my', 'tags', 'are', 'in', 'here'] 
like image 361
Hoa Avatar asked Apr 27 '12 07:04

Hoa


2 Answers

String.split() can also accept a regular expression:

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

This particular regex splits on a sequence of one or more commas or spaces, so that e.g. multiple consecutive spaces or a comma+space sequence do not produce empty elements in the results.

like image 109
Jon Avatar answered Oct 01 '22 10:10

Jon


you can use regex in order to catch any length of white space, and this would be like:

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"  
like image 33
Cemil Dogan Avatar answered Oct 01 '22 10:10

Cemil Dogan