parsings strings: extracting words and phrases [JavaScript]
A simple regular expression will do but leave the quotation marks. e.g.
'foo bar "lorem ipsum" baz'.match(/("[^"]*")|([^\s"]+)/g)
output: ['foo', 'bar', '"lorem ipsum"', 'baz']
edit: beaten to it by shyamsundar, sorry for the double answer
var str = 'foo bar "lorem ipsum" baz';
var results = str.match(/("[^"]+"|[^"\s]+)/g);
... returns the array you're looking for.
Note, however:
- Bounding quotes are included, so can be removed with
replace(/^"([^"]+)"$/,"$1")
on the results. - Spaces between the quotes will stay intact. So, if there are three spaces between
lorem
andipsum
, they'll be in the result. You can fix this by runningreplace(/\s+/," ")
on the results. - If there's no closing
"
afteripsum
(i.e. an incorrectly-quoted phrase) you'll end up with:['foo', 'bar', 'lorem', 'ipsum', 'baz']
Try this:
var input = 'foo bar "lorem ipsum" baz';
var R = /(\w|\s)*\w(?=")|\w+/g;
var output = input.match(R);
output is ["foo", "bar", "lorem ipsum", "baz"]
Note there are no extra double quotes around lorem ipsum
Although it assumes the input has the double quotes in the right place:
var input2 = 'foo bar lorem ipsum" baz'; var output2 = input2.match(R);
var input3 = 'foo bar "lorem ipsum baz'; var output3 = input3.match(R);
output2 is ["foo bar lorem ipsum", "baz"]
output3 is ["foo", "bar", "lorem", "ipsum", "baz"]
And won't handle escaped double quotes (is that a problem?):
var input4 = 'foo b\"ar bar\" \"bar "lorem ipsum" baz';
var output4 = input4.match(R);
output4 is ["foo b", "ar bar", "bar", "lorem ipsum", "baz"]