Abhijeet Abhijeet - 1 month ago 6
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']

Answer

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

Comments