The Wayback Machine - https://web.archive.org/web/20240623161758/https://www.geeksforgeeks.org/javascript-program-to-replace-multiple-characters-in-a-string/
Open In App

JavaScript Program to Replace Multiple Characters in a String

Last Updated : 17 Jun, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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.

Using replace() method

In this approach, we are using the replace() method in which we replace multiple characters by calling and passing arguments in the replace() method multiple times. The original string will remain unchanged as we are storing changes into a new variable.

Example: It describes how we can replace multiple characters in a string using the replace() method

Javascript
// Original String
let str = 
    'Welcome GeeksforGeeks, Welcome Geeks';

// Replacing characters
let newString = 
    str.replace(/W/gi, 'w').replace(/G/gi, 'g');

// Printing the result
console.log(newString);

Output
welcome geeksforgeeks, welcome geeks

Using replaceAll() method

We are using replaceAll() method which takes two arguments. We are passing the character that need to be changed and the character that will take place instead of previous one, That’s how it will replace the character/string. It can also take regular expression and function as an argument.

Example: It describes how we can replace multiple characters in a string using the replaceAll() method

Javascript
// Original string
let str = 'gppkforgppks_ns_hele';

// Replacing multiple character
let result = str
    .replaceAll('p', 'e')
    .replaceAll('_', ' ')
    .replaceAll('n', 'i')
    .replaceAll('l', 'r');

// Printing the result
console.log(result);

Output
geekforgeeks is here

Using split() and join()

The split() and join() are two separate inbuild function of JavaScript, split() is used to split a string at particular place and join() is used to join that splited string into one with some argument passed during operation performance.

Example: It describes how we can replace multiple characters in a string using the split() and join() method

Javascript
// Original String
let str = 
    'ptlcomt GttksforGttks, ptlcomt gttks';

// Replacing character
let newString = 
    str.split('p').join('w').split('t').join('e');

// Printing the result
console.log(newString);

Output
welcome GeeksforGeeks, welcome geeks

Using regular expression

In this approach we are using regular expression for checking presence of character in original string and replacing them using replace() method. Object.entries() is used for returning the array of charcter and replacemet ([key,value] pair) in “for each loop” for replacement of multiple character in one string.

Example: It describes how we can replace multiple characters in a string using regular expression

Javascript
// Given string
// which need to be changed
let str1 = "hilo geel for geels";

// Set of list which 
// need to be replaced 
// in given string
const set = {
    hilo: "Hello",
    geel: "geek",
    geels: "geeks"
};

// Arrow function for
// replacments of character
let replaceMultiple = (str, set) => {
    const regx = 
        new RegExp(Object.keys(set).join("|"), "g");
    return str.replace(regx, (x) => set[x]);
}

// Calling arrow function
const result = replaceMultiple(str1, set);

// Printing the result in 
// the console
console.log(result);

Output
Hello geek for geeks

Using reduce()

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.

JavaScript
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


Using Map for Replacement

In this approach, we utilize a map to specify the characters to be replaced and their corresponding replacements. We then iterate through the string, replacing each character according to the map. If a character is not found in the map, it remains unchanged.

Example: This demonstrates how we can replace multiple characters in a string using a map for replacement.

JavaScript
// Original String
let str = 'JavaScript is awesome';

// Map of characters to be replaced
const replaceMap = {
    'a': '4',
    'e': '3',
    's': '$',
    'o': '0'
};

// Function to replace characters using map
function replaceWithMap(str, replaceMap) {
    return str.split('').map(char => replaceMap[char] || char).join('');
}

// Replacing characters using map
let newString = replaceWithMap(str, replaceMap);

// Printing the result
console.log(newString);

Output
J4v4Script i$ 4w3$0m3

Using Object for Character Mapping

In this approach, we use the reduce method on the string’s character array to construct a new string based on a character mapping object. This method iterates over each character and replaces it according to the mapping provided in the object.

Example: This example demonstrates how to replace multiple characters in a string using Array.prototype.reduce and a mapping object.

JavaScript
// Original String
let str = 'Functional programming is powerful';

// Object for character mapping
const charMap = {
    'a': '@',
    'e': '3',
    'i': '1',
    'o': '0',
    'u': 'v',
    's': '$'
};

// Function to replace characters using reduce and mapping object
function replaceWithCharMap(str, charMap) {
    return str.split('').reduce((acc, char) => acc + (charMap[char] || char), '');
}

// Replacing characters using mapping object
let newString = replaceWithCharMap(str, charMap);

console.log(newString);

Output
Fvnct10n@l pr0gr@mm1ng 1$ p0w3rfvl


Similar Reads

Replace multiple strings with multiple other strings in JavaScript
In this article, we are given a Sentence having multiple strings. The task is to replace multiple strings with new strings simultaneously instead of doing it one by one, using JavaScript. Below are a few methods to understand: Table of Content Using JavaScript replace() method Using the JavaScript str.replaceAll() methodUsing Array.reduce() method:
2 min read
How to replace multiple characters in a string in PHP ?
A string is a sequence of characters enclosed within single or double quotes. A string can also be looped through and modifications can be made to replace a particular sequence of characters in it. In this article, we will see how to replace multiple characters in a string in PHP. Using the str_replace() and str_split() functions in PHP.The str_rep
2 min read
JavaScript Program to Replace Characters of a String
Given a String the task is to replace characters of String with a given String in JavaScript. Examples: Input: Str = Welcome to GfG strRepl = GfG newStr = GeeksOutput: Welcome to GeeksTable of Content Using map() & split() method to replace characters from StringUsing String replace() Method to replace characters from StringUsing Regular Expres
3 min read
Replace special characters in a string with underscore (_) in JavaScript
In this article, we will see how to replace special characters in a string with an underscore in JavaScript. These are the following method to do this: Table of Content JavaScript replace() MethodUsing Lodash _.replace() MethodJavaScript replace() MethodThis method searches a string for a defined value, or a regular expression, and returns a new st
2 min read
JavaScript Program for Min flips of continuous characters to make all characters same in a String
In this article, we will learn about Min flips of continuous characters to make all characters the same in a string using JavaScript. Min flips of continuous characters in a string refer to the minimum number of changes required to turn a sequence of adjacent characters into a uniform sequence, ensuring all characters are the same. Given a string c
3 min read
How to replace the names of multiple object keys with the values provided using JavaScript ?
The following approach covers how to replace the names of multiple object keys with the values provided by the user using JavaScript. Problem Statement: You are given an object which contains different key-value pairs in which key symbolizes the property and value itself is known as the property value, and you need to change one or more key's origi
4 min read
Replace Multiple Words with K in JavaScript
Sometimes, while working with Javascript strings, we may face a problem in which we have to perform a replacement of multiple words with a single word. This can have applications in many domains like day-day programming and school programming. These are the following approaches:Table of Content Using join() and split() methodsUsing Regex and join()
5 min read
How to replace multiple spaces with single space in JavaScript ?
In this article, we will see how to replace multiple spaces with a single space in JavaScript. We will have a string having multiple spaces and we need to remove those extra spaces. There are two methods to replace multiple spaces with a single space in JavaScript: Table of Content Method 1: Using replace() MethodMethod 2: Using trim(), split(), an
3 min read
How to replace characters except last with the specified mask character in JavaScript ?
In this article, we have given a number and the task is to replace the characters except for the last character with a specified mask character in JavaScript. These are the following methods: Using Naive approachUsing slice() and replace methodUsing reduce() methodExample: Let's take a number 12345678 and the masking character is * and the number o
4 min read
JavaScript Program Replace Specific Words with Another Word in a String using Regular Expressions
In this article, we are going to learn about replacing specific words with another word in a string using regular expressions. Replacing specific words with another word in a string using regular expressions in JavaScript means searching for all occurrences of a particular word or pattern within the text and substituting them with a different word
3 min read