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

159
Visualizações
JavaScript String replace vs replaceAll

ECMAScript 2021 has added a new String function replaceAll. A long time ago in a galaxy not so far away, people used split + join or regular expressions to replace all occurences of a string.

I created the following example to compare the new method to the old ones. While I could see some differences in the first case, for example I can't use replacement patterns with split + join or I need to escape special chars with RegExp(str,"g"), I can't see any difference in the second case.

What are the differences between the new method and the old ones (behaviour difference, performance, browser compatibility...) ?

const source = "abcdefabcdef";
const str1 = "abc", str2 = "xyz";
const reg1 = /abc/g, reg2 = "xyz";

//Case 1 : When we want to replace a string by another
console.log(source.split(str1).join(str2));
console.log(source.replace(new RegExp(str1,"g"),str2));
//versus
console.log(source.replaceAll(str1,str2));

//Case 2 : When we want to use a regular expression
console.log(source.replace(reg1,reg2));
//versus
console.log(source.replaceAll(reg1,reg2));

//Result = "xyzdefxyzdef"

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Collecting the documentation for replaceAll , we found the following data:

const newStr = str.replaceAll(regexp|substr, newSubstr|function)

Note: When using a regular regexp , you must set the global flag ("g"); otherwise it will throw a TypeError: "replaceAll must be called with a global RegExp".

In other words, when calling replaceAll with a regex or RegExp literal, you must use the global flag. So there doesn't seem to be much to be gained by calling replaceAll instead of just using the current replace . However, one difference with replaceAll is that passing it a string will automatically do a global replace. This is where you can save yourself a bit of typing, by not having to enter a global flag.

over 4 years ago · Santiago Trujillo 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