2

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

Ken Y-N
  • 14,644
  • 21
  • 71
  • 114
Abhijeet Ahuja
  • 5,596
  • 5
  • 42
  • 50
  • You seem to realise a regular expression may be involved (though there are other approaches), what have you tried? – RobG Oct 11 '16 at 05:27
  • Note quite a perfect duplicate, but [this C# version could be easily translated](https://stackoverflow.com/questions/14655023/split-a-string-that-has-white-spaces-unless-they-are-enclosed-within-quotes)? – Ken Y-N Oct 11 '16 at 05:29
  • iterating over each char and splitting over a space, and if a double quote is encountered skip till next is found. But that is not looking good. – Abhijeet Ahuja Oct 11 '16 at 05:29
  • 1
    There is Isaac's answer or `'...'.match(/"[^"]+"|\S+/g)`, which doesn't need *filter* to take out the trash (and handles multiple quoted phrases in the string). – RobG Oct 11 '16 at 05:37

2 Answers2

6

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

Isaac
  • 11,409
  • 5
  • 33
  • 45
1

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

RFV
  • 831
  • 8
  • 22