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:
Replace multiple strings with multiple other strings in JavaScript
Next article icon

Replace multiple strings with multiple other strings in JavaScript

Last Updated : 30 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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() method
  • Using Array.reduce() method:

Using JavaScript replace() method

This method searches a string for a defined value, or a regular expression, and returns a new string with the replaced defined value. 

Syntax: 

string.replace(searchVal, newvalue);

Example: This example uses the RegExp to replace the strings according to the object using the replace() method.

JavaScript
let str = "I have a Lenovo Laptop, a Honor Phone, and a Samsung Tab."; let Obj = {     Lenovo: "Dell",     Honor: "OnePlus",     Samsung: "Lenovo" };  function GFG_Fun() {     console.log(str.replace(/Lenovo|Honor|Samsung/gi, function (matched) {         return Obj[matched];     })); } GFG_Fun() 

Output
I have a Dell Laptop, a OnePlus Phone, and a Lenovo Tab. 

Using the JavaScript str.replaceAll() method

In this example, we will see the use of the JavaScript str.replaceAll() method for replacing multiple strings.

Example: This example shows the implementation of the above-explained appraoch.

JavaScript
const str = 'who.where_when-how'; const result = str     .replaceAll('.', '?')     .replaceAll('_', '?')     .replaceAll('-', '?');  console.log(result); 

Output
who?where?when?how 

Using Array.reduce() method:

Using Array.reduce() with replaceAll() method, the approach iterates over an array of replacement pairs, applying each replacement to the string sequentially. It uses regular expressions to globally replace occurrences of each old string with its corresponding new string.

Example: In this example we replaces multiple characters in a string with '?' using Array.reduce() and replaceAll().

JavaScript
const str = 'who.where_when-how'; const replacements = [   ['.', '?'],   ['_', '?'],   ['-', '?'] ];  const result = replacements.reduce((acc, [oldStr, newStr]) => {   return acc.replaceAll(oldStr, newStr); }, str);  console.log(result);  

Output
who?where?when?how 

Using JavaScript String.split() and Array.join() Method

This method involves using split() to break the string at each target substring and then using join() to reassemble the string with the new substring in place of the target substrings.

Example: In this example, we will replace multiple substrings using split() and join() methods.

JavaScript
let str = "I have a Lenovo Laptop, a Honor Phone, and a Samsung Tab."; let replacements = {     "Lenovo": "Dell",     "Honor": "OnePlus",     "Samsung": "Lenovo" };  function replaceMultiple(str, replacements) {     for (let [oldStr, newStr] of Object.entries(replacements)) {         str = str.split(oldStr).join(newStr);     }     return str; }  console.log(replaceMultiple(str, replacements)); 

Output
I have a Dell Laptop, a OnePlus Phone, and a Lenovo Tab. 




Next Article
Replace multiple strings with multiple other strings in JavaScript

P

PranchalKatiyar
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • javascript-string
  • JavaScript-DSA
  • JavaScript-Questions

Similar Reads

    Create a string with multiple spaces in JavaScript
    We have a string with extra spaces and if we want to display it in the browser then extra spaces will not be displayed. Adding the number of spaces to the string can be done in the following ways. In this article, we are going to learn how to Create a string with multiple spaces in JavaScript. Below
    3 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 Usin
    5 min read
    JavaScript - How to Replace Multiple Spaces with a Single Space?
    Here are the various methods to replace multiple spaces with a single space in JavaScript.1. Using replace() Method with Regular Expression (Most Common)The replace() method combined with a regular expression is the most efficient way to replace multiple spaces with a single space.JavaScriptconst s1
    2 min read
    JavaScript - How to Match Multiple Parts of a String Using RegExp?
    In JavaScript, the regular expression (RegExp) object provides a powerful mechanism to search, match, and manipulate strings. One of the common use cases is matching multiple parts of a string that satisfy a certain pattern. You can easily do this using global (g) and other RegExp features.1. Using
    3 min read
    Replace all Occurrences of a Substring in a String in JavaScript
    Given a String, the task is to replace all occurrences of a substring using JavaScript. The basic method to replace all substring of a string is by using string.replaceAll() method.The string.replaceAll() method is used to search and replace all the matching substrings with a new string. We can use
    2 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