0
var mystring = 'Hello test1 "test2 but one word" test3 test4  '; 

var mystring_ar= mystring.split(/\s+/);

okay I have this /\s+/ expression so I can seperate from spaces but my problem is I want to seperate from spaces and regular expression should not seperate word if words surrounded by ", like "test2 but one word" For example below:

'Hello test1 "test2 but one word" test3 test4  '.split(regex) 
=> ['Hello','test1','test2 but one word','test3','test4']

is that possible?

Edited I have found half solution but not completed below code seperate correctly but only works for words for example if string is a/b/as d , it will not seperate it to a/b/as and d,it will seperate it to a,b,as,d

keywords = keywords.match(/\w+|"[^"]+"/g);

But I think solution should be with split.It should work like seperate from whitespaces and don't seperate inside of ""

Jake
  • 3
  • 3
  • Related: [Split a string by whitespace, keeping quoted segments, allowing escaped quotes](https://stackoverflow.com/questions/4031900/split-a-string-by-whitespace-keeping-quoted-segments-allowing-escaped-quotes) – Jonathan Lonowski Jan 27 '17 at 03:46
  • @JonathanLonowski Thank you it solved my problem :) – Jake Jan 27 '17 at 04:16
  • @JonathanLonowski but I got problem with solution that I have found in link .It uses ` /\w+|"[^"]+"/g ` but it only accept words, but I need seperate from whitespaces but if it is between `"asd asd asd"` It should not seperate them.But it seems like `/\w+|"[^"]+"/g ` this expression also seperate `t1/t2 to t1 and t2 which is not correct for this problem` – Jake Jan 27 '17 at 05:59
  • @JonathanLonowski I think solution should be with split.It should work like seperate from whitespaces and don't seperate inside of "".How can I do that? – Jake Jan 27 '17 at 06:06
  • Then use `\S` instead of `\w`, and put the quoted expression first: `/"[^"]*"|\S+/g` (with `match`). – trincot Jan 27 '17 at 06:10
  • @trincot thank you it worked like a charm :) – Jake Jan 27 '17 at 06:23
  • OK, I've put that as an answer with a little optional addition. – trincot Jan 27 '17 at 06:24

1 Answers1

0

This works easier with match. To match any non-white-space, you can use the opposite of \s, i.e. \S. As quotes also match with \S, you then also need to first test for the quote, and only put the \S as alternative of that. Maybe you also want to ignore a quoted part, when it is followed immediately by a non-space, like "thi"s word" should maybe not become ['thi','s','word'], but['"thi"s','word']. That you can do with negative look ahead: (?!\S). All together that becomes:

/"[^"]*"(?!\S)|\S+/g
trincot
  • 317,000
  • 35
  • 244
  • 286