So if I have a string like:
'boss: "Person 1" AND occupation: "Engineer"'
Is there a way I can split the string into an array like such:
['boss:', '"Person 1"', 'AND', 'occupation:', '"Engineer"']
I have lots of different regex splits and multiple argument splits and I can't seem to achieve this. Any ideas?
FYI: yes I would like to leave in the quotations surrounding Person 1 and Engineer and maintain the spaces in whatever is between quotations
Thanks!
-
1what have you tried? where are you stuck?Cruiser– Cruiser2017年06月28日 19:31:08 +00:00Commented Jun 28, 2017 at 19:31
2 Answers 2
var input = 'boss: "Person 1" AND occupation: "Engineer"';
console.log(input.match(/"[^"]*"|[^ ]+/g));
// Output:
// [ 'boss:', '"Person 1"', 'AND', 'occupation:', '"Engineer"' ]
Explanation
You want to match two kinds of things:
- Things without spaces in them (since spaces separate terms).
- Things in quotes (where spaces are allowed).
The regular expression here consists of two parts:
"[^"]*"- This matches a double quote, followed by any number of non-double-quote characters, followed by another double quote.[^ ]+- This matches one or more non-space characters.
The two are combined with a pipe (|), which means "or." Together, they match both types of things you want to find.
1 Comment
".*?" instead. I think that's perfectly fine too.If console.log prints an array, it surrounds each string element with
apostrophes, so you see the apostrophes only in console output.
If you want to get a string formatted the way you want, use the following script:
var str = 'boss: "Person 1" AND occupation: "Engineer"';
var pat = /"[^"]+"|\S+/g;
var res1 = str.match(pat);
var result = "['" + res1.join("', '") + "']";