Ultimately I'm trying to turn this:
var msg = '-m "this is a message" --echo "another message" test arg';
into this:
[
'-m',
'this is a message',
'--echo',
'another message',
'test',
'arg'
]
I'm not quite sure how to parse the 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 that will work, but man does that seem like a fickle and backwards way of accomplishing what I want. I'm sure you guys have a much better way than creating a placeholder string before the split.
To split a string by multiple spaces, call the split() method, passing it a regular expression, e.g. str. trim(). split(/\s+/) . The regular expression will split the string on one or more spaces and return an array containing the substrings.
The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.
To add a space between characters of a string, call the split() method on the string to get a character array, then call the join() method on the array to join the characters with a space separator.
To remove all white spaces from String, use the replaceAll() method of String class with two arguments, i.e.
with exec(), you can allready take the strings without the 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With