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!
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.
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.
split("(? =\"[^\"]. *\")");
Use the String. replaceAll() method to remove all double quotes from a string, e.g. str. replaceAll('"', '') .
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.
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