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

123
Visualizações
better way to replace string with various scenarios in javascript

How to replace special characters for different pattern of same string in javascript

am passing one string at a time and below are string patterns

var str1="2456 #02-567"
var result = str1.replace(/#/g, '')

var str1="2-567 2456"
var result = str1.replace(/^/g, '0')
for these strings

2456 #02-567 , 2456 02-567, 2456 2-567,2456 #2-567

Expected Output 
2456 02-567 
 ===========
for these strings
#02-567 2456 , 2-567 2456, 02-567 2456, #2-567 2456

Expected Output 
02-567 2456

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

0

May be there is a clever solution, but this should work:

let str = ["2456 #02-567" , "2456 02-567", "2456 2-567","2456 #2-567","#02-567 2456" , "2-567 2456", "02-567 2456", "#2-567 2456","1234 12-345","1234 #12-345","#12-345 1234"];
//1234 12-345" or "1234 #12-345" or "#12-345 1234"
for(let st of str)
 console.log(st.replace(/#?(\d)?(\d-)/g ,replacer))
 
 function replacer(match, p1, p2, offset, string){
  let replaceSubString = p1 || "0";
  replaceSubString += p2;
  return replaceSubString;
 }

I'm using a captouring group (expression in the parenthesis in the regular expression) that can be referenced in the second parameter of replace function with $1 (1 because is the first captouring group). The ? instead point that the character is optional.

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