0

Hope all of you are doing nice and being safe.

I'm using node JS and what I want to achieve is the following: I want to make an array with all the ocurrences that matches a certain regex. I want to find in a string all the ocurrences of numbers that have a format like this one: %{00001}

For example, if I have the following text:

Example text %{00001} with some %{00002} examples %{00003}

The match method should return the following array with three elements:

["%{00001}" , "%{00002}" , "%{00003"]

This is the code I am using currently. The problem is that I only obtain the first value it gets. For this example, it returns an array with %{00001}, that's all. And supposedly, this method can find all the ocurrences and make an array, so my guess is that I'm probably using it wrong. I tried this regex in the regex101 website and it returns three matches, so now I'm a little confused and I would appreciate some help.

let textRegex = "This is a test: %{00000}  This is the name: %{00003} . This is the description: %{00001}";

let arrayRegex = textRegex.match("%{[0-9]{5}}").map(String);

What am I doing wrong? I made several searches before making this post, but couldn't find anything that helps me :(

Thanks for your help!

Best regards, Sergio

  • Use `g` flag: `let arrayRegex = textRegex.match(/%{[0-9]{5}}/g)` => `['%{00000}', '%{00003}', '%{00001}']` – Wiktor Stribiżew Oct 15 '21 at 08:41
  • @WiktorStribiżew That worked for me! Thank you very much. Just a little doubt, because I'm a little noob using NodeJs. It's "correct" to use the match expression without being between "" ? Thank you! – Sergio García Oct 15 '21 at 08:45
  • 1
    It's a [regex literal](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) – CherryDT Oct 15 '21 at 08:47
  • @SergioGarcía It is up to you what form to use, constructor or regex literal notations, `.match(/%{[0-9]{5}}/g)` = `.match(new RegExp("%{[0-9]{5}}", "g")`, however, MDN says (see link in the comment above) that regex literal notation should be preferred with static regexps. – Wiktor Stribiżew Oct 15 '21 at 08:49

0 Answers0