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
  • 13,857
  • 21
  • 69
  • 105
Abhijeet
  • 5,006
  • 3
  • 36
  • 44
  • 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 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
  • 10,812
  • 5
  • 30
  • 43
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
  • 751
  • 6
  • 21