Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split javascript string into a max of 2 parts?

I have strings like this

FOO hello world
BAR something else
BISCUIT is tasty
CAKE is tasty too

The goal is to split string once after the first word. So far I'm using this

# coffeescript
raw = 'FOO hello world'
parts = raw.split /\s/
[command, params] = [parts.shift(), parts.join(' ')]
command #=> FOO
params #=> hello world

I don't like this for two reasons:

  1. It seems inefficient
  2. I'm rejoining the string with a ' ' character. The real string parameters can be split by either a ' ' or a \t and I'd like to leave the originals intact.

Any ideas?

like image 562
Mulan Avatar asked Dec 16 '12 20:12

Mulan


1 Answers

Try this out:

[ command, params ] = /^([^\s]+)\s(.*)$/.exec('FOO hello world').slice(1);
like image 73
Nathan Wall Avatar answered Sep 22 '22 10:09

Nathan Wall