Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
JavaScript - How to Replace Multiple Characters in a String?
Next article icon

JavaScript - How to Replace Multiple Characters in a String?

Last Updated : 26 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Here are the various methods to replace multiple characters in a string in JavaScript.

1. Using replace() Method with Regular Expression

The replace() method with a regular expression is a simple and efficient way to replace multiple characters.

JavaScript
const s1 = "hello world!"; const s2 = s1.replace(/[elo]/g, "x");  console.log(s2); 

Output
hxxxx wxrxd! 
  • [elo] matches the characters e, l, and o.
  • The g flag ensures all occurrences are replaced.

2. Using replaceAll() Method

The replaceAll() method can replace all instances of specific characters or strings without the need for a regular expression.

JavaScript
const s1 = "hello world!"; const s2 = s1.replaceAll("l", "x").replaceAll("o", "y");  console.log(s2);  

Output
hexxy wyrxd! 

This is suitable for replacing multiple characters sequentially, but you need to chain multiple replaceAll() calls.

3. Using split() and join() Method

You can replace characters by splitting the string and joining it back with the desired character.

JavaScript
const s1 = "hello world!"; const s2 = s1.split("l").join("x").split("o").join("y");  console.log(s2); 

Output
hexxy wyrxd! 

This approach works well when replacing one character at a time and avoids regular expressions.

4. Using Regular Expressions for Multiple Replacements

If you need to replace multiple characters with different replacements, you can use a regular expression with a callback function in replace().

JavaScript
const s1 = "hello world!"; const s2 = s1.replace(/[elo]/g, (char) => {     const replacement = { e: "x", l: "y", o: "z" };     return replacement[char] || char; });  console.log(s2);  

Output
hxyyz wzryd! 

This approach provides flexibility and is efficient for handling complex replacement logic.

5. Using reduce() Method

The reduce() method can be used to apply multiple replacements iteratively.

JavaScript
const s1 = "hello world!"; const replacements = [["l", "x"], ["o", "y"]];  const s2 = replacements.reduce(     (str, [target, replacement]) =>          str.split(target).join(replacement),     s1 );  console.log(s2);  

Output
hexxy wyrxd! 

This is useful when you have a dynamic list of characters to replace.

6. Using a Map for Replacement

A Map can store character mappings, and you can iterate through the string to apply replacements.

JavaScript
const s1= "hello world!"; const map = new Map([["e", "x"], ["l", "y"], ["o", "z"]]);  const s2 = [...s1].map((char) => map.get(char) || char).join("");  console.log(s2); 

Output
hxyyz wzryd! 

This approach is efficient and clean when dealing with predefined replacements.

7. Using an Object for Character Mapping

Similar to a Map, an object can store character mappings for replacements.

JavaScript
const s1 = "hello world!"; const map = { e: "x", l: "y", o: "z" };  const s2 = s1     .split("")     .map((char) => map[char] || char)     .join("");  console.log(s2); 

Output
hxyyz wzryd! 

This is a simple alternative to Map and works well for smaller datasets.

8. Using Chained replace() Calls

You can also chain multiple replace() calls for replacing different characters.

JavaScript
const s1 = "hello world!"; const s2 = s1.replace("e", "x").replace("l", "y").replace("o", "z");  console.log(s2); 

Output
hxylz world! 

This is simple for a small number of replacements but becomes difficult to manage for larger sets.

Which Approach Should You Use?

ApproachWhen to Use
Using replace() with RegexBest for replacing multiple characters in one go with a consistent replacement.
Using replaceAll()Ideal for replacing a single character or substring globally.
Using split() and join()Good for replacing one character at a time without regex.
Using Regular Expressions with CallbackBest for replacing multiple characters with different replacements.
Using reduce()Useful when handling dynamic lists of replacements.
Using Map/Object for ReplacementEfficient for predefined character mappings.
Chained replace() CallsSimple but limited to small sets of replacements.

The replace() with regular expression and object mapping methods are the most efficient for replacing multiple characters.


Next Article
JavaScript - How to Replace Multiple Characters in a String?

M

meetahaloyx4
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • javascript-string
  • JavaScript-DSA
  • JavaScript-Program

Similar Reads

    JavaScript Program to Swap Characters in a String
    In this article, We'll explore different approaches, understand the underlying concepts of how to manipulate strings in JavaScript, and perform character swaps efficiently. There are different approaches for swapping characters in a String in JavaScript: Table of Content Using Array ManipulationUsin
    6 min read
    JavaScript- Remove Last Characters from JS String
    These are the following ways to remove first and last characters from a String:1. Using String slice() MethodThe slice() method returns a part of a string by specifying the start and end indices. To remove the last character, we slice the string from the start (index 0) to the second-to-last charact
    2 min read
    JavaScript Program to Remove Last Character from the String
    In this article, we will learn how to remove the last character from the string in JavaScript. The string is used to represent the sequence of characters. Now, we will remove the last character from this string. Example: Input : Geeks for geeks Output : Geeks for geek Input : Geeksforgeeks Output :
    3 min read
    JavaScript - Remove all Occurrences of a Character in JS String
    These are the following ways to remove all occurrence of a character from a given string: 1. Using Regular ExpressionUsing a regular expression, we create a pattern to match all occurrences of a specific character in a string and replace them with an empty string, effectively removing that character
    2 min read
    Replace Specific Words in a String Using Regular Expressions in JavaScript
    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
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences