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

195
Views
How to determine matched group's offset in JavaScript's replace?

Terms

Matched pattern

indicate all matched portions of the input string, which all reside inside the match array. These are all instances of your pattern inside the input string.

Matched groups

indicate all groups to catch, defined in the RegEx pattern. (The patterns inside parentheses, like so: /format_(.?)/g, where (.?) would be a matched group.) These reside within matched patterns.

We can determine the offset of the matched pattern easily, for example by using replace() :

// offset of the matched pattern is : arguments[arguments.length - 2]
'lorem ipsum dolor sit amet'.replace(/ip(\w+)[ ]/g, function() {
     console.log(JSON.stringify(arguments, undefined, 2));
})
The result of execution will be :

{
  "0": "ipsum ",
  "1": "sum", 
  "2": 6,
  "3": "lorem ipsum dolor sit amet"
}

So, how to programmatically determine the offset of the matched group instead of the whole matched pattern?

In this case, the offset of "sum" in above example, which is 8.

Both of the text and regex are user input. So, hardcoded way to generate the offset of the group is not an option.

By the way, regex101.com can generates these offsets fairly fast, So there is must be away to do this.: enter image description here

about 4 years ago · Juan Pablo Isaza
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!