I have tried to split strings in JS like..
'a b c' => ['a','b','c']
'a bb cc dd' => ['a','bb','cc','dd]
'a "bb cc" dd' => ['a','bb cc', 'dd']
"a 'bb cc' dd" => ['a','bb cc', 'dd']
How do I do it in JS regexp?
I have tried
/\w+|"(?:\\"|[^"])+"/g
but it returns…
'a b c' => ['a','b','c']
'a bb cc dd' => ['a','bb','cc','dd]
'a "bb cc" dd' => ['a','"bb cc"', 'dd']
"a 'bb cc' dd" => ['a','bb','cc', 'dd']
Suppose you have a string:
You can quite easily match the tokens using:
That pattern:
The result tokens, however, will be wrapped in quotes.
Here is an example of a way to remove these quotes:
This has a few tricks, but the idea is that we pick the group that isn’t empty (which is a falsey value is JavaScript). You could achieve the same with
exec, but the code is messier in my opinion.Working example: http://jsfiddle.net/snS62/ (warning – alerts)
To also allow escaped characters, you may use: