How to use reduce() In Javascript
The reduce() method iterates over each character of the string, building a new string by checking if the character is in the list of characters to replace. If it is, the replacement character is added to the accumulator; otherwise, the original character is added.
Example: The replaceMultipleCharsReduce function replaces specified characters in a string with a given replacement using reduce(). It checks each character and builds the new string accordingly.
function replaceMultipleCharsReduce(str, charsToReplace, replacement) {
return str.split('').reduce((acc, char) =>
acc + (charsToReplace.includes(char) ? replacement : char), ''
);
}
console.log(replaceMultipleCharsReduce("hello world", "eo", "*"));
Output
h*ll* w*rld
JavaScript Program to Replace Multiple Characters in a String
We are going to learn how we can replace Multiple Characters in a String. We have to replace multiple characters in a string using the inbuilt function or any other method.
Table of Content
- Using replace() method
- Using replaceAll() method
- Using split() and join()
- Using regular expression
- Using reduce()
- Using Map() Method
Contact Us