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

JavaScript Program to Replace Characters of a String

Last Updated : 03 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 = Geeks
Output: Welcome to Geeks

Using map() & split() method to replace characters from String

In this approach, split(‘ ‘) is used to split the string into an array of words. Then, map() is used to iterate over each word in the array. If the word is equal to oldWord, it is replaced with newWord; otherwise, the word remains unchanged. Finally, join(‘ ‘) is used to join the array back into a string

Example: Here we will split the given string “Hello user, welcome to GeeksforGeeks” and replace the “Hello” with “Hi”.

JavaScript
const str = "Hello user, welcome to GeeksforGeeks";
oldWord='Hello';
newWord='Hi'
const replacedString=str.split(' ').map(word => word === oldWord ? newWord : word).join(' ');
console.log(replacedString);

Output
Hi user, welcome to GeeksforGeeks

Using String replace() Method to replace characters from String

JavaScript string.replace() method is used to replace a part of the given string with another string or a regular expression. The original string will remain unchanged.

Example: Here we will replace the “GfG” with “Geeks” on the given string “Welocome to GfG”.

JavaScript
// JavaScript program to Replace
// Characters of a string
const str = 'Welcome to GfG';
const replStr = 'GfG';
const newStr = 'Geeks';

const updatedStr = str.replace(replStr, newStr);

console.log(updatedStr);

Output
Welcome to Geeks

Using Regular Expression to replace characters from String

To replace all occurrences of a string in JavaScript using a regular expression, we can use the regular expression with the global (g) Flag.

Example: In this example we will replace “Welcome” with “Hello” in the given string “Welcome GeeksforGeeks, Welcome geeks”.

JavaScript
const str = 'Welcome GeeksforGeeks, Welcome geeks';
const searchString ="Welcome";
const replacementString ="Hello";

let regex = new RegExp(searchString, 'g');

let replacedString = 
    str.replace(regex, replacementString);

console.log(replacedString);

Output
Hello GeeksforGeeks, Hello geeks

Using split and join Method to Replace Characters from a String

In this approach, the split method is used to divide the string into an array of substrings based on the substring we want to replace. Then, the join method is used to combine the array back into a string, with the new substring replacing the old one.

Example: Here we will replace “GfG” with “Geeks” in the given string “Welcome to GfG”.

JavaScript
const str = 'Welcome to GfG';
const oldStr = 'GfG';
const newStr = 'Geeks';

const updatedStr = str.split(oldStr).join(newStr);

console.log(updatedStr);

Output
Welcome to Geeks





Similar Reads

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() methodUsing replaceAll() methodUsing split() and join()Using regular expression Using reduce()Using Map for ReplacementUsing Object for Characte
5 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 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
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
Difference Between String.prototype.replace() and String.prototype.replaceAll() in JavaScript
The String.prototype.replace and String.prototype.replaceAll are frequently used to the modify strings. Understanding the differences between these methods is crucial for the effective string handling. This article explores the characteristics, applications and examples of both the replace and replaceAll methods. These are the following topics that
3 min read
How to replace a string by another string in AngularJS ?
In this article, we will see how to select a string from the text and replace it with another string using AngularJS and will understand it through the illustrations. The replace() method can be used to search the particular character(s), which is getting replaced with a specific character(s) & return a new generated string. Syntax: string.repl
2 min read
How to globally replace a forward slash in a JavaScript string ?
In JavaScript, a forward slash serves multiple purposes such as division operator, string character, etc. In this article, we will see how to globally replace a forward slash in a JavaScript string. Below are the methods used to globally replace a forward slash in a JavaScript string: Table of Content Using replace() method with a regular expressio
3 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 maintain the integrity of the original data. Understand
5 min read
How to replace all dots in a string using JavaScript ?
We will replace all dots in a string using JavaScript. There are multiple approaches to manipulating a string in JavaScript. Table of Content Using JavaScript replace() MethodUsing JavaScript Split() and Join() Method Using JavaSccript reduce() Method and spread operatorUsing JavaScript replaceAll() MethodUsing JavaScript for loopUsing JavaScript m
4 min read
How to replace all occurrences of a string in JavaScript ?
Replacing all occurrences of a string in JavaScript is a common task in text processing. It involves identifying and substituting specific substrings within a larger string. This capability is crucial for tasks such as data cleaning, formatting, and transforming text in various applications. These are the following methods to replace all occurrence
3 min read
JavaScript URLify a given string (Replace spaces is %20)
In this article, we are going to discuss how can we URLify a given string using JavaScript. In which we will be transforming the spaces within the input strings into the "%20" sequence. The process of URLLification consists of replacing these spaces with the '%20' encoding. This task is essential for creating valid URLs, and query parameters. Examp
6 min read
Replace all Occurrences of a Substring in a String in JavaScript
In JavaScript, a string is a sequence of characters represented with quotation marks. We are given a string and we need to replace all occurrences of a substring from the given string. Table of Content Using replace() method with regular expressionUsing indexOf() and slice() methodsUsing replaceAll() methodUsing the replace() method with regular ex
2 min read
Replace Duplicate Occurrence in a String in JavaScript
JavaScript String is a sequence of characters, typically used to represent text. It is useful to clean up strings by removing any duplicate characters. This can help normalize data and reduce unnecessary bloat. There are several ways to replace duplicate occurrences in a given string using different JavaScript methods which are as follows: Table of
3 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 text and substituting them with a different word
4 min read
Smallest Window in a String Containing all the Characters of Another String using JavaScript
Given two strings, "str" (the larger string) and "pattern" (the smaller string), the task is to find the smallest window in "str" that contains all the characters of "pattern" in any order using JavaScript. Examples: Input: str = "ADOBECODEBANC"pattern = "ABC"Output: BANCInput: str = "this is a test string"pattern = "tist";Output: t striTable of Co
3 min read
Javascript Program to Minimize characters to be changed to make the left and right rotation of a string same
Given a string S of lowercase English alphabets, the task is to find the minimum number of characters to be changed such that the left and right rotation of the string are the same. Examples: Input: S = “abcd”Output: 2Explanation:String after the left shift: “bcda”String after the right shift: “dabc”Changing the character at position 3 to 'a' and c
3 min read
JavaScript Program to Print All Duplicate Characters in a String
In this article, we will learn how to print all duplicate characters in a string in JavaScript. Given a string S, the task is to print all the duplicate characters with their occurrences in the given string. Example: Input: S = “geeksforgeeks”Output:e, count = 4g, count = 2k, count = 2s, count = 2Table of Content Using For Loop in JavaScriptUsing S
5 min read
JavaScript Program to Access Individual Characters in a String
In this article, we are going to learn about accessing individual characters from the given string. Accessing individual characters in a string means retrieving a specific character from the string using its index position (zero-based) or iterating through each character one by one. Example: Input : str = GeeksforGeeksOutput :Character at index 0:
4 min read
JavaScript Program to Check if String Follows Order of Characters Defined by a Pattern or Not
In this JavaScript article, we will see the solution to the problem of checking if a string follows the order of characters defined by a pattern or not. We have given a string and pattern as the input and our task is to develop a program that will check whether the input string follows the same pattern according to the pattern given. Example: To so
4 min read
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 ManipulationUsing String ConcatenationUsing Regular ExpressionsUsi
6 min read
JavaScript Program to Check Whether a String Starts and Ends With Certain Characters
In this article, We are going to learn how can we check whether a string starts and ends with certain characters. Given a string str and a set of characters, we need to find out whether the string str starts and ends with the given set of characters or not. Examples: Input: str = "abccba", sc = "a", ec = "a"Output: YesInput: str = "geekfor geeks",
3 min read
JavaScript Program to Check for Repeated Characters in a String
In this article, we are going to see various methods with which you can detect repeated characters in a string. Checking for repeated characters in a string involves examining the string's content to identify if any character occurs more than once. This helps detect duplications or repetitions within the text. Input: Str = “geeksforgeeks”Output:e,
6 min read
JavaScript Program to Mirror Characters of a String
Our task is to mirror characters from the N-th position up to the end of a given string, where 'a' will be converted into 'z', 'b' into 'y', and so on. This JavaScript problem requires mirroring the characters in a string starting from a specified position. There are various approaches available to accomplish this, such as utilizing loops and maps.
6 min read
JavaScript Program to Remove Non-Alphanumeric Characters from a String
We will see how to remove non-alphanumeric characters from a string in JavaScript. Non-alphanumeric characters are symbols, punctuation, and whitespace. Removing them from a string This task can be useful when you want to clean up user inputs, sanitize strings, or perform various text processing operations. There are multiple approaches to removing
4 min read
JavaScript Program to Check if a String Contains Any Digit Characters
In this article, we will see how to check if a string contains any digit characters in JavaScript. Checking if a string contains any digit characters (0-9) in JavaScript is a common task when we need to validate user input or perform specific actions based on the presence of digits in a string. We will explore every approach to check if a string co
5 min read
JavaScript Program to Validate String for Uppercase, Lowercase, Special Characters, and Numbers
In this article, we are going to learn how can we check if a string contains uppercase, lowercase, special characters, and numeric values. We have given string str of length N, the task is to check whether the given string contains uppercase alphabets, lowercase alphabets, special characters, and numeric values or not. If the string contains all of
4 min read
JavaScript Program to Remove First and Last Characters from a String
This article will show you how to remove the first and last characters from a given string in JavaScript. There are two methods to remove the first and last characters in a string. Table of Content 1. Using String slice() Method2. Using String substring() Method3. Using Array Methods4. Using String substr() Method:5. Using Regular Expression and St
4 min read
JavaScript Program to Remove Consecutive Duplicate Characters From a String
We are going to implement a JavaScript program to remove consecutive duplicate characters from a string. In this program, we will eliminate all the consecutive occurrences of the same character from a string. Example: Input: string: "geeks" Output: "geks"Explanation :consecutive "e" should be removedTable of Content Using Iterative LoopUsing Regula
5 min read
JavaScript Program to Find Missing Characters to Make a String Pangram
We have given an input string and we need to find all the characters that are missing from the input string. We have to print all the output in the alphabetic order using JavaScript language. Below we have added the examples for better understanding. Examples: Input : welcome to geeksforgeeksOutput : abdhijnpquvxyzInput : The quick brown fox jumpsO
7 min read