Reputation: 735
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.
Upvotes: 0
Views: 1058
Reputation: 5623
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.
Upvotes: 4
Reputation: 4777
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).
Upvotes: 1