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 Words with K in JavaScript
Next article icon

Replace Multiple Words with K in JavaScript

Last Updated : 19 Feb, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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() methods
  • Using Regex and join() method
  • Using for Loop and replace() method
  • Using map() method

Using join() and split() methods

The combination of the join() and split() functions can be used to perform this task. In this, we split the string into words, check and replace the list words using join and list.

Example: This example shows the use of the join() and split() methods to replace words.

JavaScript
// Initialize string let test_str =      'Geeksforgeeks is best for geeks and CS';  // Print original string console.log("The original string is : " + test_str);  // Initialize word list let word_list = ["best", 'CS', 'for'];  // Initialize replace word let repl_wrd = 'gfg';  // Replace multiple words with K // Using split(), map() and includes() let res = test_str.split(' ').map(word =>     word_list.includes(word) ? repl_wrd : word).join(' ');  // Print result console.log("String after multiple replace : " + res); 

Output
The original string is : Geeksforgeeks is best for geeks and CS String after multiple replace : Geeksforgeeks is gfg gfg geeks and gfg 

Time Complexity: O(n)

Space Complexity: O(n)

Using Regex and join() method

Now we will use combination of regex and join() method to get the desired result. In JavaScript, the join() method and regular expressions (regex) are both valuable tools for working with text, but they serve distinct purposes. The join() method combines elements of an array or iterable into a single string, using a specified separator between each element. Regex are powerful patterns used to search, extract, and manipulate text based on defined patterns.

Example: This example shows the use of regular expression to replace the word.

JavaScript
// Initialize string let test_str =      'Geeksforgeeks is best for geeks and CS';  // Print original string console.log("The original string is : " + test_str);  // Initialize word list let word_list = ["best", 'CS', 'for'];  // Initialize replace word let repl_wrd = 'gfg';  // Create a regular expression pattern from word_list let pattern = new RegExp(word_list.join('|'),     'g');  // Replace multiple words with K let res = test_str.replace(pattern, repl_wrd);  // Print the result console.log("String after multiple replace : "     + res); 

Output
The original string is : Geeksforgeeks is best for geeks and CS String after multiple replace : Geeksgfggeeks is gfg gfg geeks and gfg 

Time Complexity: O(n)

Space Complexity: O(n)

Using for Loop and replace() method

Now we will use for loop and replace() method to get the required output. The replace() method will be used to search a string for a value. It usually returns a new string with the value(s) replaced. So we will run the for loop till the size of word_list.

Example: This example shows the use of loop and replace() method to replace the word.

JavaScript
// Initialize string let test_str = `Geeksforgeeks is best      for computer science and IT`;  // Print original string console.log("The original string is : " + test_str);  // Initialize word list let word_list = ["best", 'IT', 'for'];  // Initialize replace word let repl_wrd = 'gfg';  // Replace multiple words with K for (let i = 0; i < word_list.length; i++) {     test_str = test_str.replace(new RegExp(word_list[i],         'g'), repl_wrd); }  // Print the result console.log("String after multiple replace : " + test_str); 

Output
The original string is : Geeksforgeeks is best      for computer science and IT String after multiple replace : Geeksgfggeeks is gfg      gfg computer science and gfg 

Time Complexity: O(n*m) where n is the length of the input string and m is the number of words in the word_list.

Space Complexity: The space complexity is O(n), where n is the length of the input string test_str.

Using map() method

Another method to solve the problem is by splitting the string into an array of words, then using the map() method to iterate over each word and replace it if it exists in the word_list. Finally, we join the modified array back into a string.

Example: This example shows the use of map() method to replace the word.

JavaScript
// Initialize string let test_str = `Geeksforgeeks is best      for computer science and IT`;  // Print original string console.log("The original string is : "     + test_str);  // Initialize word list let word_list = ["best", 'CS', 'for'];  // Initialize replace word let repl_wrd = 'gfg';  // Replace multiple words with K let res = test_str.split(' ').map(word => {     if (word_list.includes(word)) {         return repl_wrd;     }     return word; }).join(' ');  // Print the result console.log("String after multiple replace : "     + res); 

Output
The original string is : Geeksforgeeks is best      for computer science and IT String after multiple replace : Geeksforgeeks is gfg      for computer science and IT 

Time Complexity: O(n)

Space Complexity: O(n)


Next Article
Replace Multiple Words with K in JavaScript

S

snikitasha19
Improve
Article Tags :
  • JavaScript
  • Web Technologies

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 s
    2 min read
    JavaScript string replace() Method
    JavaScript replace() method is used for manipulating strings. It allows you to search for a specific part of a string, called a substring, and then replace it with another substring. What's great is that this method doesn't alter the original string, making it ideal for tasks where you want to maint
    5 min read
    JavaScript replaceAt() Method
    The replaceAt() method is useful for removing the character at a given place. Unfortunately, the replaceAt() method is not a built-in method in JavaScript. It would need to be defined by the user in order to use it. One possible implementation of a replaceAt() function could take a string and two in
    2 min read
    Wildcard Pattern Matching in JavaScript
    In this article, we will see Pattern matching with wildcards which is an encountered problem, in the field of computer science and string manipulation. The objective is to determine whether a given wildcard pattern matches a string or not. In this article, we will discuss the step-by-step algorithm
    4 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
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