mutantfrogs
mutantfrogs

Reputation: 3

Regular Expression puts in more than I want it too

I'm writing a discord bot currently and I am trying to have a command that replaces a string to whatever you write. It does this by finding what is in quotes and extracting it. Problem is, it seems to take the message with quotes and the message without quotes and then puts them both in.

The commands are written like this...

!setmoogie title "title of movie"

Here is my code:

let moogieTitle = "To Be Announced...";
let moogieDescription = "";
let moogieTime = "Friday at 8pm EST";
let moogieImage = "";
let moogieColor = "ab732b";
let moogieFooter = "Anything subject to change at any time.";

const regex = /"([^"]*)"/;

switch (args[1]) {
  case "title":
    moogieTitle = regex.exec(message.content);
    message.channel.send("Updated title.");
    break;

  case "description":
    moogieDescription = regex.exec(message.content);
    message.channel.send("Updated description.");
    break;

  case "image":
    moogieImage = regex.exec(message.content);
    message.channel.send("Updated image.");
    break;

  case "time":
    moogieTime = regex.exec(message.content);
    message.channel.send("Updated time.");
    break;

  case "color":
    moogieColor = regex.exec(message.content);
    message.channel.send("Updated embed color.");
    break;

  case "footer":
    moogieFooter = regex.exec(message.content);
    message.channel.send("Updated embed footer.");
    break;

  case "preset":
    switch (args[2]) {
      case "tba":
        moogieTitle = "To Be Announced...";
        moogieDescription = "";
        moogieTime = "Friday at 8pm EST";
        moogieImage = "";
        moogieColor = "ab732b";
        message.channel.send("Updated embed to TBA preset.");
        break;
    }
    break;
}
break;

and this is the output:

output

I'm new to regular expression and a helping hand would be nice, thanks!

Upvotes: 0

Views: 77

Answers (1)

Lioness100
Lioness100

Reputation: 8412

When you capture a part of a string using regex (capture), it returns an array. For example:

var content = 'abcdefg'
const regex = /(abc)defg/;

// this returns an array of the full string,
// and then all the individual captures
const res = regex.exec(content);
console.log('Full Array: ', res);

console.log('Whole String: ', res[0]) // returns first element in array (whole string)
console.log('First Capture: ', res[1]) // returns second element in array (first capture)


In conclusion, you should be grabbing the second element in the array .exec() returns to get only what is inside the quotes:

regex.exec(message.content)[1]

Upvotes: 1

Related Questions