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

163
Visualizações
replacing the string values using grouping

I have url string, where i want insert one string and stitch it back together. I am able to add the first two set of strings but the last group I am not able to

let string = 'http://stackoverflow.com/questions/1/replace-text'
    .replace(/(\/\/[^\/]+)?\/.*/, '$1/testing/$2');
    
    console.log(string)

Here I want to attach the remaining part after the first slash which should be $2 but I am not able to achieve it. How can I achieve this what my expected output is

http://stackoverflow.com/testing/questions/1/replace-text
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You don't need to match the rest of the URL. Just match the part you want to replace, and the rest will be kept in the replacement.

let string = 'http://stackoverflow.com/questions/1/replace-text'
    .replace(/\/\/[^\/]+/, '$&/testing');
    
    console.log(string)

about 4 years ago · Juan Pablo Isaza Relatório

0

You could use lookaheads to insert into the string without removing anything:

(?<!:|\/)(?=\/)|$

  • The (?<!:\/) is a negative lookbehind to ignore the protocol header (://)
  • The (?=\/) is a positive lookahead that checks for a single slash
  • The $ accounts for a string without a slash at the end

const regex = /(?<!:|\/)(?=\/)|$/;

const testString = 'http://stackoverflow.com/questions/1/replace-text';

console.log(testString.replace(regex, '/testing'))

about 4 years ago · Juan Pablo Isaza Relatório

0

Not quite a fancy solution but it works.

let string = 'http://stackoverflow.com/questions/1/replace-text'
// http://stackoverflow.com/testing/questions/1/replace-text
let parts = string.split("/")
let newString = parts[0] + "//"+ parts[2]  + "/testing/" +  parts[3] +"/" +  parts[4]  + "/" +   parts[5] 

console.log( newString , "newString" )

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