Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

203
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda