Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I split a string by space in javascript, except when the spaces occur between "quote"? [duplicate]

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.

like image 885
Chev Avatar asked Mar 14 '13 21:03

Chev


People also ask

How do you separate strings based on spaces?

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.

How do you separate text in JavaScript?

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.

How do you leave a space in JavaScript?

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.

How do you get rid of the middle space in a string?

To remove all white spaces from String, use the replaceAll() method of String class with two arguments, i.e.


1 Answers

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
like image 101
GameAlchemist Avatar answered Oct 01 '22 22:10

GameAlchemist