razorxan
razorxan

Reputation: 516

Parse a string as a command line input in Javascript

I need a help on this string parsing. What i want to do is to parse a string like this one using Javascript.

"myname" secondarg "third argument" andso on

to give me a result like

[0] => myname
[1] => secondarg
[2] => third argument
[3] => andso
[4] => on

EDIT:

"test" " foo" bar "hello world" " hello "

to

[0] => 'test'
[1] => ' foo'
[2] => 'bar'
[3] => 'hello world'
[4] => ' hello '

Upvotes: 3

Views: 329

Answers (1)

Joseph Myers
Joseph Myers

Reputation: 6552

function argsFrom(string) {
    return string.match(/'[^']*'|"[^"]*"|\S+/g) || [];
}

That is pretty decent, but it doesn't deal with escaped quotation marks, etc. It's pretty complicated to have a complete solution, just as complicated as parsing CSV.

Javascript code to parse CSV data

Upvotes: 3

Related Questions