Node.js - How to parse arguments passed via an IRC chat message

615 views Asked by At

EDIT: I am using the twitch-irc library from Github for Node.js, installed via npm.

This is such a basic question and I feel like a bit of an idiot for asking, but...

if (message.toLowerCase().indexOf('!os') === 0) {

}

Let's say I used this code, how would I add if statements for the arguments that the user provides? By this, I mean after typing !os, they would create a space and type something else, this would either be the 0th or 1st argument.

Would it be possible to just use this?:

if (message.toLowerCase().indexOf('kernel') === 4) {

}

In pseudo code, I want to do:

if (firstargument === 'kernel') {
    //Do stuff.
}

Thank you for your time.

2

There are 2 answers

3
galactocalypse On BEST ANSWER

You could simply use var args = message.match(/\S+/g) to get all the arguements (including '!os') in an array and use them as you wish.

e.g.

var args = message.match(/\S+g/);
var cmd = args[1]; //do a length check before accessing args[1] though
switch (cmd) {
    case 'kernel':
    // do stuff
    break;
    case 'process':
    // do stuff
    break;
    default:
    // invalid command
}
1
Blubberguy22 On

What you said would make sense to do, but you should remove white space (spaces) so that a command like !os kernel will still work (note the two spaces).

Do that like this:

if (message.replace(/\s\g, '').toLowerCase().indexOf('kernel') === 3) {
//Do stuff
}