Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
86
rated 0 times [  87] [ 1]  / answers: 1 / hits: 20398  / 11 Years ago, sun, april 28, 2013, 12:00:00

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!


More From » regex

 Answers
43
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.

[#78556] Saturday, April 27, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
moriah

Total Points: 201
Total Questions: 100
Total Answers: 82

Location: Tuvalu
Member since Sun, Sep 4, 2022
2 Years ago
;