0

Quick question

If I am making a command like the following

!add {gamename}{gamedescription}{gamestatus}

How would I know that each argument is inside of the {}

I know the actual command is my first arg

 let args = message.content.substring(PREFIX.length).split(" ");
 switch(args[0]) {
    case 'status':

PREFIX being the '!'

Just not sure how I set argument 1 has the first string inside of the first {} and so on.

2 Answers 2

4

This regular expression will do the trick. Test it out below.

const regex = /{(.+?)}/g;
const string = '!add {game}{game description}{game status}';

const args = [];

let match;
while (match = regex.exec(string)) args.push(match[1]);

console.log(args);

Explanation:
To see how the regex works and what each character does, check it out here. About the while loop, it iterates through each match from the regex and pushes the string from the first capturing group into the arguments array.

Small, but worthy note:
. does not match line breaks, so arguments split up into multiple lines within a message will not be included. To prevent this, you could replace any new line character with a space before using the regex.

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

Comments

1

You can use a regular expression to capture substrings in a pattern.

const message = {
  content: '!add {gamename}{gamedescription}{gamestatus}'
};

const matches = message.content.match(/^!([a-zA-Z]+) {([a-zA-Z]+)}{([a-zA-Z]+)}{([a-zA-Z]+)}/);
if (matches) {
  console.log(matches[1]); // add
  console.log(matches[2]); // gamename
  console.log(matches[3]); // gamedescription
  console.log(matches[4]); // gamestatus
}

When the string matches the pattern, the matches object has substrings surrounded by () in matches[1], matches[2], matches[3] and matches[4]. matches[0] has the entire matched string (!add {gamename}{gamedescription}{gamestatus} in this case).

6 Comments

So it would work even if gamedescription is a lot of text?
If it's a text with spaces and symbols, the subpattern {([a-zA-Z]+)} needs to be adjusted according to which characters you want to allow in it. How long can it be? Can it have line breaks?
it's a description of a game server... What was shown above was the command format. This is how the command could be.
!add {RektServers}{This is the best damn server in the freaking world!}{Running}
That's why I am asking if there is a way to split by {} so it knows the arguments are inside the {} <---curly brackets
|

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.