Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript split string by space, but ignore space in quotes (notice not to split by the colon too)

I need help splitting a string in javascript by space (" "), ignoring space inside quotes expression.

I have this string:

var str = 'Time:"Last 7 Days" Time:"Last 30 Days"'; 

I would expect my string to be split to 2:

['Time:"Last 7 Days"', 'Time:"Last 30 Days"'] 

but my code splits to 4:

['Time:', '"Last 7 Days"', 'Time:', '"Last 30 Days"'] 

this is my code:

str.match(/(".*?"|[^"\s]+)(?=\s*|\s*$)/g); 

Thanks!

like image 302
Elad Kolberg Avatar asked Apr 28 '13 09:04

Elad Kolberg


People also ask

How do you split a string when there is a space?

To split a string with space as delimiter in Java, call split() method on the string object, with space " " passed as argument to the split() method. The method returns a String Array with the splits as elements in the array.

What can I use instead of split in Javascript?

Slice( ) and splice( ) methods are for arrays. The split( ) method is used for strings. It divides a string into substrings and returns them as an array.

How do you split a string with double quotes?

split("(? =\"[^\"]. *\")");

How do you strip quotes in Javascript?

Use the String. replaceAll() method to remove all double quotes from a string, e.g. str. replaceAll('"', '') .


1 Answers

s = 'Time:"Last 7 Days" Time:"Last 30 Days"' s.match(/(?:[^\s"]+|"[^"]*")+/g)   // -> ['Time:"Last 7 Days"', 'Time:"Last 30 Days"'] 

Explained:

(?:         # non-capturing group   [^\s"]+   # anything that's not a space or a double-quote   |         #   or…   "         # opening double-quote     [^"]*   # …followed by zero or more chacacters that are not a double-quote   "         # …closing double-quote )+          # each match is one or more of the things described in the group 

Turns out, to fix your original expression, you just need to add a + on the group:

str.match(/(".*?"|[^"\s]+)+(?=\s*|\s*$)/g) #                         ^ here. 
like image 143
kch Avatar answered Oct 02 '22 04:10

kch