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

288
Visualizações
How to regex replace a query string with matching 2 words?

I have a url and I want to replace the query string. For example

www.test.com/is/images/383773?wid=200&hei=200

I want to match the wid= and hei= and the numbers don't have to be 200 to replace the whole thing so it should look like this.

Expected www.test.com/is/images/383773?@HT_dtImage

So I've tried doing but it only replaced the matching wei and hei.

const url = "www.test.com/is/images/383773?wid=200&hei=200"

url.replace(/(wid)(hei)_[^\&]+/, "@HT_dtImage")

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

I would just use string split here:

var url = "www.test.com/is/images/383773?wid=200&hei=200";
var output = url.split("?")[0] + "?@HT_dtImage";
console.log(output);

If you only want to target query strings havings both keys wid and hei, then use a regex approach:

var url = "www.test.com/is/images/383773?wid=200&hei=200";
var output = url.replace(/(.*)\?(?=.*\bwid=\d+)(?=.*\bhei=\d+).*/, "$1?@HT_dtImage");
console.log(output);

about 4 years ago · Juan Pablo Isaza Relatório

0

You can match either wid= or hei= until the next optional ampersand and then remove those matches, and then append @HT_dtImage to the result.

\b(?:wid|hei)=[^&]*&?

The pattern matches:

  • \b A word boundary to prevent a partial word match
  • (?:wid|hei)= Non capture group, match either wid or hei followed by =
  • [^&]*&? Match 0+ times a char other than &, and then match an optional &

See a regex demo.

let url = "www.test.com/is/images/383773?wid=200&hei=200"
url = url.replace(/\b(?:wid|hei)=[^&]*&?/g, "") + "@HT_dtImage";
console.log(url)

about 4 years ago · Juan Pablo Isaza Relatório

0

You can make use of lookaround using regex /\?.*/

enter image description here

const url = 'www.test.com/is/images/383773?wid=200&hei=200';

const result = url.replace(/\?.*/, '?@HT_dtImage');
console.log(result);

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