Skip to content
Advertisement

How to identify a pattern in a string in nodejs

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

Advertisement

Answer

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');
Advertisement