Abhijeet Abhijeet - 1 year ago 69
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 Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download