muffin guy
muffin guy

Reputation: 23

How can I limit variables to take in specific values in a string, if I don't know how long the values will be?

I am trying to create variables to accept arguments for a discord mute command I am trying to make. I tried to make three variables, mutee, time, and reason. The command is intended to be in this format !mute [mutee, time, reason].

const mutee = JSON.parse(message.content.slice(7));
//gets the member u want to mute
const time = JSON.parse(message.content.slice(8 + mutee.length()));
//gets the time you want the user to be muted for
const reason = JSON.parse(message.content.slice(9 + mutee.length() + time.length()));
//gets the reason for the mute

When the variable mutee takes in the arguments for the member that is intended to be muted it will also take in the time frame and reason and time will take in reason with the time. How can I limit mutee to take in only mutee and time to only take in time, if I don't know the how long each of those values will be?

Upvotes: 1

Views: 98

Answers (1)

Elitezen
Elitezen

Reputation: 6720

You may want to consider implementing Arguments if you plan to have similar commands down the line. However I'll show you a quick example.


Look at it this way: Your message content looks something like this:

!mute @User 10m Spam

How do we know what's what? The spacing.

[!mute ... @User ... 10m ... Spam]

We can split the message by a space to give us an array of substrings, each substring being the individual words by doing

const words = message.content.split(' ');
// words => ['!mute', '@User', '10m', 'Spam'];

However, this will split up the reason into multiple pieces if it's greater than 1 word. I'll get to that in a second.

First let's separate the mutee and the time

const words = message.content.split(' ');
const mutee = words[1]; // '@User'
const time = words[2]; // '10m'

We can assign the rest of the array to one variable by using .join(). This will automatically join all substrings into one string to be the reason.

// Slice will remove the first 2 elements which we known to be the mutee and time

const reason = words.slice(3).join(' '); 
// reason => 'Spam' ... And anything in front!

Your Final Code will look like this

const words = message.content.split(' ');
const mutee = words[1];
const time = words[2];
const reason = words.slice(3).join(' ');

In ES6, You can do this for a bit of syntactic sugar.

const words = message.content.split(' ');
let [, mutee, time, ...reason] = words;
reason = reason.join(' ');

Upvotes: 3

Related Questions