Abhijeet Abhijeet - 4 months ago 28
Javascript Question

Fetch words in a sentence

I have string -

My name is "foo bar" I live in New York

Now I want to split it to an array but words in double quotes should be considered as one.

I have tried
input.split(' ')
but need some help how to handle strings inside double quotes.

I want output as
['My', 'name', 'is', '"foo bar"', 'I', 'live', 'in', 'New', 'York']


Something along the lines of

var str = 'My name is "foo bar" I live in New York';
console.log(str.split(/ |(".*?")/).filter(v=>v));

should do the trick