Abhijeet Ahuja
Abhijeet Ahuja

Reputation: 5950

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']

Upvotes: 2

Views: 91

Answers (2)

RFV
RFV

Reputation: 839

The regex code (?:".*")|\S+ will do exactly that.

(?:".*") means any sequence between two mathcing " signs
| means OR
\S+ means any sequence of any non-whitespace characters

Upvotes: 1

Isaac
Isaac

Reputation: 11805

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

Upvotes: 6

Related Questions