Emilia Emilia - 6 months ago 20
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
['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

You can use match()

console.log(
  '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])

console.log(res);

Regex explanation here

Regular expression visualization

Comments