<\/script>')

How to split a line by space in javascript, except when spaces occur between "quotes"?

I end up trying to do this:

var msg = '-m "this is a message" --echo "another message" test arg'; 

in it:

 [ '-m', 'this is a message', '--echo', 'another message', 'test', 'arg' ] 

I'm not quite sure how to parse a string to get the desired results. This is what I have so far:

 var msg = '-m "this is a message" --echo "another message" test arg'; // remove spaces from all quoted strings. msg = msg.replace(/"[^"]*"/g, function (match) { return match.replace(/ /g, '{space}'); }); // Now turn it into an array. var msgArray = msg.split(' ').forEach(function (item) { item = item.replace('{space}', ' '); }); 

I think this will work, but the person makes it seem like a volatile and reverse way of doing what I want. I am sure that you guys are much better than creating a placeholder string before the split.

+4
source share
3 answers

with exec (), you can allready take strings without quotes:

 var test="once \"upon a time\" there was a \"monster\" blue"; function parseString(str) { var re = /(?:")([^"]+)(?:")|([^\s"]+)(?=\s+|$)/g; var res=[], arr=null; while (arr = re.exec(str)) { res.push(arr[1] ? arr[1] : arr[0]); } return res; } var parseRes= parseString(test); // parseRes now contains what you seek 
+5
source

Instead of split you can match :

 var msg = '-m "this is a message" --echo "another message" test arg'; var array = msg.match(/"[^"]*"|[^\s"]+/g); console.log(array); 

gives:

  ['-m',
   '"this is a message"',
   '--echo',
   '"another message"',
   'test',
   'arg'] 
+4
source

It’s hard to guess what you would prefer as a solution, but one approach would be to separate the quotes (this does not imply enclosed quotes), and then separate each alternate element with spaces:

 result = []; msg.split("\"").map(function(v, i ,a){ if(i % 2 == 0) { result = result.concat(v.split(" ").filter(function(v){ return !v; })); } else { result.push(v); } }); 

Here is a demo: http://jsfiddle.net/eL7cc/

+1
source

Source: https://habr.com/ru/post/1469370/


All Articles