Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

194
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda