1

I have the following problem that I have not been able to solve for several hours:

What I want to do is that when I receive a string, identify a pattern in said string and be able to use it later, for example when receiving the text:

"Hello this is an example message, the hashtag of the day is #Phone, you can use it wherever you want"

what I want to do is identify that #Phone and extract it from all that text and for example then be able to make a console.log() of that word that is with the #. So that the result of the console.log is only Phone, for example, or the data that has the #

I have the following code:

const prefix = "#";

client.on("message", function(message) {
  if (!message.content.includes(prefix)) return;

  const commandBody = message.content.slice(prefix.length);
  const args = commandBody.split(' ');
  const command = args.shift().toUpperCase();
  console.log(command)
});

This what returns me is the first element of the text without its first letter, in the case that the text is "Hello, how are you !try this", what it shows is only "ello", and I need it to only show " try"

Jabibi
  • 35
  • 2
  • 7

1 Answers1

2

Use a regular expression to match # (or !) followed by letters or non-space characters or whatever sort of text you want to permit afterwards:

const prefix = '!';
const pattern = new RegExp(prefix + '([a-z]+)', 'i');
const getMatch = str => str.match(pattern)?.[1];
console.log(getMatch('Hello, how are you !try this'));

If the prefix may be a special character in a regular expression, escape it first:

function escapeRegex(string) {
    return string.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}

const pattern = new RegExp(escapeRegex(prefix) + '([a-z]+)', 'i');
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Hi, thanks for aswer too fast, i have this problem const getMatch = str => str.match(pattern)?.[1]; ^ SyntaxError: Unexpected token '.' the code right now is : client.on("message", function(message) { const prefix = '!'; const pattern = new RegExp(prefix + '([a-z]+)', 'i'); const getMatch = str => str.match(pattern)?.[1]; if (message.author.bot) return; if (!message.content.includes(prefix)) return; console.log(getMatch('Hello, how are you !try this')); }); – Jabibi Mar 12 '21 at 16:41
  • If your environment doesn't understand optional chaining, I'd highly recommend updating it to something that implements the current version of the ECMAScript standard. Optional chaining is great, better not to dumb down your source code just for the sake of an obsolete environment. But if you had to, you could do `const result = str.match(pattern); return result ? result[1] : null` instead of the optional chaining – CertainPerformance Mar 12 '21 at 16:59
  • Thanks for that, i need update nodejs right? i update my vstudio code, and downloading nodejs to see .I hope this works, thanks!!! – Jabibi Mar 12 '21 at 17:11