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

112
Visualizações
JavaScript replace method for multiple/different searchValues and newValues

The closest I've found to talking about what I wanna do is this thread.

JavaScript has a very nice replace method: string.replace(searchValue, newValue)

If I have a string like this: var str = '/by-the-pound/c/252' and I want to replace the '/' with empty strings (essentially removing it), I can do something like this: str.replace(/[/]/g, "");

and if I want to replace 'c' with '-', I can do this: str.replace(/c/g, "-");

I understand that we can chain this like so: str.replace(/[/]/g, "").replace(/c/g, "-"); and it will give us this: 'by-the-pound-252'

But what if I had a very long string, and wanted to replace, say 10 different characters, with 10 different values? That would be a very long, chained-up line of code with 10 .replace methods.

TL;DR

Is there a way to use one .replace but have multiple searchValue's and newValue's.

I've tried something like this (and many more), but nothing has worked:

str.replace(/[/]|[c]/g, ""|"-")
str.replace(/[/]|[c]/g, "","-");
str.replace(/[/],[c]/g, "","-");
str.replace(/[/|c]/g, [""|"-"]);
str.replace(/[/|c]/g, "","-");

Why do I want to do this? For brevity, for clean/easy-to-read code, etc...

Thank you for your time.

UPDATE: The answer to my question is probably, No. There probably isn't a way to do what I asked, which was: Is there a way to use one .replace but have multiple searchValue's and newValue's? I looked through whatever docs I could find but didn't see any working examples of that. I realize that there are different ways of accomplishing what I want to do. I was able to create a function, for example, using an array of pairs like @DaveNewton suggested (similar to what both @MauroAguilar and @Ryan have done), and this worked fine, but I just wanted to know if you could do this in one simple line. Probably a wasted post. Mods feel free to remove. Thank you to all for taking the time.

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

0

I don't see any problem with chaining but if what you want is some kind of utility that automates this process for you then you could write a simple utility function like this:

const replacer = (str, values) => 
    values.reduce((fstr, [val, rep]) => 
        fstr.replace(val, rep), str);

const replacer = (str, values) => 
    values.reduce((fstr, [val, rep]) => 
        fstr.replace(val, rep), str);

const str = 'Peter Piper Picked a Peck of pickled peppers';

const result = replacer(str, [
  [/p/ig, 'B'],
  [/\s/g, '-'],
  [/-/g, '/']
]);

console.log(result);

about 4 years ago · Juan Pablo Isaza Relatório

0

I would make a list of replacements that can be added to and looped over.

export interface StringReplacement {
    find: string;
    replace: string;
}

Create a list of StringReplacement

const stringReplacements: StringReplacement[] = [
    {
        find: 'val1',
        replace: 'val2'
    },
    {
        find: 'val5',
        replace: 'val6'
    }
]

Then whenever you are ready to transform

const inputString = 'this val1 is the val5 input string.';

stringReplacements.forEach(replacement => 
    inputString = inputString.replace(replacement.find, replacement.replace)
);
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