Finlay Roelofs Finlay Roelofs - 2 months ago 9
Javascript Question

Javascript, split a string in 4 pieces, and leave the rest as one big piece

I'm building a Javascript chat bot for something, and I ran into an issue:

I use

to tokenize my input like this:

tokens = message.split(" ");

Now my problem is that I need 4 tokens to make the command, and 1 token to have a message.
when I do this:
!finbot msg testuser 12345 Hello sir, this is a test message

these are the tokens I get:
["!finbot", "msg", "testuser", "12345", "Hello", "sir,", "this", "is", "a", "test", "message"]

However, how can I make it that it will be like this:
["!finbot", "msg", "testuser", "12345", "Hello sir, this is a test message"]

The reason I want it like this is because the first token (
) is the call, the second (
) is the command, the third (
) is the user, the fourth (
) is the password (as it's a password protected message thing... just for fun) and the fifth (
) is the actual message.

Right now, it would just send
because I only use the 5th token.

the reason why I can't just go like
message = token[4] + token[5];
etc. is because messages are not always exactly 3 words, or not exactly 4 words etc.

I hope I gave enough information for you to help me.
If you guys know the answer (or know a better way to do this) please tell me so.



You could revert to regexp given that you defined your format as "4 tokens of not-space separated with spaces followed by message":

function tokenize(msg) {
    return (/^(\S+) (\S+) (\S+) (\S+) (.*)$/.exec(msg) || []).slice(1, 6);

This has the perhaps unwanted behaviour of returning an empty array if your msg does not actually match the spec. Remove the ... || [] and handle accordingly, if that's not acceptable.