How to have a Discord bot return the number of words in a message

Tags: , ,

client.on('message', message => {
    if (!message.content.startsWith(prefix) || return;

    const args = message.content.slice(prefix.length).trim().split(/ +/);
    const command = args.shift().toLowerCase();

    if (command === 'args-info') {
      if (!args.length) {
        return`You didn't provide any arguments, ${}!`);
      } else if (args[0] === 'foo') {
      }`Command name: ${command}nArguments: ${args}`);`Second argument: ${args[1]}`);`Arguments: {}`);

This is the part that is relevant to the question.

If you message the bot “Here are my arguments what do you think about that?”, I want it to return:

Command name: args-info
Arguments: here,are,my,arguments,what,do,you,think,about,that
Second argument: are
**Arguments Length: 10** 

I need to figure out the command that counts the number of words in a sentence and change this:`Arguments: ${}`);

I’m not familiar with Discord.js functions and which one can count a character string. I will look some more but I haven’t found anything yet. The reason I ask is this person put it as an example in his code but he never shows the code of how to return the answer and I’m just curious.


args is already an array of the words, so you can print the .length property of that. It will return the number of elements (words in this case) in that array.`Arguments length: ${args.length}`);

You can find some comments in the following code to explain it better:

client.on('message', (message) => {
  if (!message.content.startsWith(prefix) || return;

  // args is an array of all the words
  // including "args-info"
  const args = message.content
    // .slice() removes the prefix from the message content
    // .trim() removes spaces from both ends
    // .split() creates a new array by dividing the string
    // it splits the string everywhere it finds one or more spaces
    .split(/ +/);

  // the shift() method removes the first element
  // it removes args-info in this case
  const command = args.shift().toLowerCase();

  if (command === 'args-info') {
    if (!args.length) {
        `You didn't provide any arguments, ${}!`,
    if (args[0] === 'foo') {
    }`Command name: ${command}`);`Arguments: ${args}`);`Second argument: ${args[1]}`);
    // args.length is the number of words`Arguments length: ${args.length}`);

And it seems to be working as expected:

enter image description here

Source: stackoverflow