Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

209
Views
global Regexp is returning incorrect index inside for loop

I am trying to remove a timestamp (formatted as numbers dash numbers) from a string. In the process I experimented with global RegExp. I came up with the following code:

for(let filename of ["123-123_aaa_bbb_ccc","aaa_bbb_ccc_129-999"])
{
  let s=filename.split("_")
  let globalRegex = new RegExp('^\d+\-\d+$', 'g');
  for(let si of s){
    if(globalRegex.test(si)) break
  }
  console.log(`match found at: `,globalRegex.lastIndex)
}

which returns:

match found at:  0
match found at:  0

My questions are:

  1. How do I correctly remove the timestamp from the string?
  2. Why is the regexp returning 0 for both runs?
  • I expected (0 then 3 index to be returned) It seems like the state of the global regex isnt being reinitialized for the second run. However I assumed it would be, since it is redeclared inside the for loop
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

There are quite a few issues here:

  • You get 0s because your regex does not match, and it does not match because you defined the regex string inside a regular string literal, thus, losing all single backslashes. The pattern must be set with a regex literal, let globalRegex = /^\d+\-\d+$/; (see Why this javascript regex doesn't work?). Note the absence of the g flag, if you use it with RegExp#test(), you must not use g flag to avoid issues (see Why does a RegExp with global flag give wrong results?).
  • Even if you define the regex properly you will get 0s as output because a /^\d+\-\d+$/ regex can and will only match at the start of the string (Index=0). You seeem to want to get the IDs of the "words" or "tokens" in the string, so you need to count them.

So, you could re-write the code as

for(let filename of ["123-123_aaa_bbb_ccc","aaa_bbb_ccc_129-999"])
{
  let result = -1;
  let s=filename.split("_")
  let globalRegex = /^\d+\-\d+$/;
  for (const [index, si] of s.entries()) {
    if(globalRegex.test(si)) {
        result = index
        break
    }
  }
  console.log(`match found at: `, result)
}

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!