Reputation: 33
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!
Upvotes: 0
Views: 52
Reputation: 30971
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("', '") + "']";
Upvotes: 0
Reputation: 60143
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:
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.
Upvotes: 1