Home > Enterprise >  JavaScript replace method for multiple/different searchValues and newValues
JavaScript replace method for multiple/different searchValues and newValues

Time:08-04

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.

CodePudding user response:

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);

CodePudding user response:

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)
);
  • Related