Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

113
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda