Emilia Emilia - 1 year ago 100
Node.js Question

Parse string to commandline-like array

I'm making an interactive app with Node that (obviously) takes user input. I have that much working, but some of the input has spaces, which a

.split(' ')
call would mess with.

Example of what's happening:

> foo "hello world" bar

What I want to happen:

> foo "hello world" bar
['foo','hello world','bar']

I've tried looking for an npm package, but haven't had any luck.

Edit: I'm aware I can use regex, but I have no idea what the proper sequence would be.

Answer Source

You can use match()

  'foo "hello world" bar'.match(/"[^"]+"|\w+/g)

Regex explanation here

Regular expression visualization

If you want to avoid " then use captured group regex with exec()

var str = 'foo "hello world" bar';
var reg = /"([^"]+)"|\w+/g,
  m, res = [];

while (m = reg.exec(str))
  res.push(m[1] || m[0])


Regex explanation here

Regular expression visualization

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download