0

I need to exrtact a command and arguments (Node.js) from users input, for example a user can write one of this cases :

g!p first video is good

g! play latest game was bad

g!play latest game was bad

in the 1st case : command = "p" and Args="first video is good .... to the end of the string"

in the 2nd case : command = "play" and Args="latest game was .... to the end of the string"

...

const command = message.toLowerCase().split("!", 2).join("");
const Args = message.content.split(" ")[2];

if(command === 'play' or command === 'p'){........}

i tryed the split function with "!" but it doesn't work

1 Answer 1

1

Match a !, followed by zero or more space characters, then match and capture the next word (non-space characters), then use a different group to match and capture everything else:

const extract = (str) => {
  const match = str.match(/!\s*(\S+)\s+(.+)/);
  if (!match) {
    return 'No match';
  }
  const [, command, args] = match;
  console.log("Command:" + command, "Args:" + args);
};
extract('g!p first video is good');
extract('g! play latest game was bad');
extract('g!play latest game was bad');

Sign up to request clarification or add additional context in comments.

2 Comments

we can also input just a command like : "g!invit" no need for args, but with that regex its always : 'No match' ??
Make the part after the command optional then: (?:\s+(.+))? so that it's in an optional non-capturing group

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.