The Wayback Machine - https://web.archive.org/web/20240915130022/https://www.geeksforgeeks.org/javascript-string-replace-method/
Open In App

JavaScript string replace() Method

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

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. Understanding how to use replace() can enhance your ability to work with strings effectively in JavaScript.

Syntax: 

str.replace(value1, value2);

Parameters:

  • value1: is the regular expression that is to be replaced
  • value2: is a string that will replace the content of the given string. 

Return Values:

It returns a new string with replaced items.

Example 1: Below is an example of the string.replace() Method. 

javascript
let string = 'GeeksForGeeks';
let newstring = string.replace('GeeksForGeeks', 'GfG');
console.log(newstring); 

Output
GfG

Explanation:

  • A string string is assigned the value 'GeeksForGeeks'.
  • The replace() method is called on string, searching for the substring 'GeeksForGeeks' and replacing it with 'GfG'.
  • Since the entire string 'GeeksForGeeks' matches, it is replaced with 'GfG'.
  • The new string 'GfG' is assigned to the variable newstring.
  • newstring is logged to the console.

Example 2: Here the contents of the string GeeksForGeeks will be replaced with gfg. 

javascript
 // Assigning a string
 let string = 'GeeksForGeeks is a CS portal';
    
 // Calling replace() method
 let newstring = string.replace(/GeeksForGeeks/, 'gfg');
 
 // Printing replaced string
 console.log(newstring);  

Output
gfg is a CS portal

Explanation:

  • A string string is assigned the value 'GeeksForGeeks is a CS portal'.
  • The replace() method is called on string, using a regular expression to match the substring 'GeeksForGeeks' and replace it with 'gfg'.
  • The first occurrence of 'GeeksForGeeks' in the string is replaced with 'gfg'.
  • The modified string is assigned to the variable newstring.
  • The replaced string newstring is logged to the console.

Example 3: Below is an example of the string.replace() Method. 

javascript
// Taking a regular expression
let re = /GeeksForGeeks/;

// Taking a string as input
let string = 'GeeksForGeeks is a CS portal';

// Calling replace() method to replace
// GeeksForGeeks from string with gfg
let newstring = string.replace(re, 'gfg');

// Printing new string with replaced items
console.log(newstring);

Output
gfg is a CS portal

Explanation:

A regular expression re is defined to match the substring 'GeeksForGeeks'.

  • A string string is assigned the value 'GeeksForGeeks is a CS portal'.
  • The replace() method is called on string, using the regular expression re to match the substring 'GeeksForGeeks' and replace it with 'gfg'.
  • The first occurrence of 'GeeksForGeeks' in the string is replaced with 'gfg'.
  • The modified string is assigned to the variable newstring.
  • The replaced string newstring is logged to the console.

We can also replace the same words at multiple places in a string. It is known as a global replacement.

Example 4: This example explains replacing of various similar words in a string.

JavaScript
// Assigning a string
let string = 'GeeksForGeeks is a CS portal.' +
    'In GeeksForGeeks we can learn multiple languages.' +
    'geeksForGeeks is a great place.';

// Calling replace() method
let newstring = string.replace(/GeeksForGeeks/g, 'Gfg');

// Printing replaced string
console.log(newstring);

Output
Gfg is a CS portal.In Gfg we can learn multiple languages.geeksForGeeks is a great place.

Explanation:

A multi-line string string is assigned with multiple occurrences of the substring 'GeeksForGeeks'.

  • The replace() method is called on string, using a regular expression with the global flag (/g) to match all occurrences of the substring 'GeeksForGeeks' case-sensitively and replacing them with 'Gfg'.
  • All occurrences of 'GeeksForGeeks' in the string are replaced with 'Gfg'.
  • The modified string is assigned to the variable newstring.
  • The replaced string newstring is logged to the console.

Supported Browsers: 

  • Google Chrome 1 and above
  • Edge 12 and above
  • Firefox 1 and above
  • Opera 4 and above
  • Safari 1 and above

JavaScript String replace() method- FAQS

What is the replace() method in JavaScript and how does it work?

The replace() method in JavaScript is used for manipulating strings. It allows you to search for a specific part of a string, known as a substring, and replace it with another substring. This method returns a new string with the specified replacements and does not alter the original string. This functionality is particularly useful for tasks that require string modifications without affecting the original data.

What are the parameters used in the replace() method?

The replace() method takes two parameters:

1. value1: This can be either a substring to search for or a regular expression to find the match in the string.

2. value2: This is the string that will replace the content matched by value1.

What is the return value of the replace() method?

The replace() method returns a new string where the specified value1 (substring or regular expression match) is replaced with value2. If no matches are found, the original string is returned unchanged.

How does the replace() method handle regular expressions?

When a regular expression is passed as the first parameter ( value1 ), the replace() method can leverage advanced pattern matching capabilities. The regular expression can include flags such as g for global replacements, which replace all occurrences in the string, and i for case-insensitive matches, among others. This allows for more powerful and flexible string manipulation compared to simple substring replacement.

How can you replace all occurrences of a substring in JavaScript?

To replace all occurrences of a substring in JavaScript, you can use the replace() method with a global regular expression (/pattern/g). This instructs the replace() method to find and replace all matches in the string, not just the first one. For example, using /substring/g as the first parameter will ensure that every instance of substring in the string is replaced.



Previous Article
Next Article

Similar Reads

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
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
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 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
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
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
TypeScript String replace() Method
The replace() method in TypeScript is used to find matches between a regular expression or a substring and a string, replacing the matched substring with a new substring or the value returned by a function. Syntaxstring.replace(regexp/substr, newSubStr/function[, flags]);Parameter: This method accepts five parameters as mentioned above and describe
2 min read
What is replace() Method in JavaScript ?
In JavaScript, the replace() method is a string method that is used to search for a specified substring or pattern in a string and replace it with another substring or the result of a function. It returns a new string with the replacements applied while leaving the original string unchanged. Syntax:string.replace(searchValue, newValue)string: The o
1 min read
JavaScript Replace() Method
The replace() method in JavaScript is used to search a string for a value or any expression and replace it with the new value provided in the parameters. The original string is not changed by this method. Syntax: string.replace(searchVal,newVal) Parameter: This method accepts two parameters. searchVal: It is the value that we want to replace in the
2 min read
How to replace all occurrences of a string using Vue.js filters ?
In this article, we are going to learn how to replace all occurrences of a particular word with some other word using filters in VueJS. Vue is a progressive framework for building user interfaces. Filters are a functionality provided by Vue components that let you apply formatting and transformations to any part of your template dynamic data. The f
2 min read
Less.js String replace() Function
Less.js is a simple CSS pre-processor that facilitates the creation of manageable, customizable, and reusable style sheets for websites. It is preferable since CSS is a dynamic style sheet language. LESS can be utilized by many different browsers because it is versatile. Web browsers can only use CSS that has been developed and processed using a co
3 min read
How to replace String in PHP ?
Replacing a string in PHP involves substituting parts of a string with another string. Common methods include str_replace() for simple replacements, preg_replace() for pattern-based replacements, substr_replace() for positional replacements, and str_ireplace() for case-insensitive replacements. Each method serves different use cases. Table of Conte
3 min read
How to replace a text in a string with another text using PHP ?
A string is a sequence of one or more characters. A string is composed of characters, each of which can be replaced easily in the script. A large number of in-built PHP methods can be used to perform string replacements. Table of Content Using str_replace() method - The str_replace() Using str_ireplace() method Using preg_replace()Using substr_repl
4 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 lowercase letters with an other character in JavaScript ?
Given a string and the task is to replace all lowercase letters from a string with the other characters in JavaScript. There are some approaches to replace the character that are described below: JavaScript replace() Method: This method searches a string for a defined value, or a regular expression, and returns a new string with the replaced define
2 min read
How to replace plain URL with link using JavaScript ?
Given a plane URL, the task is to replace the plain URLs with the links. This problem can be solved with the help of Regular Expressions. Approach: Using RegExp and replace() MethodRegExp - This looks for the URL in the provided text.This RegExp parses the URL and puts the address to the $1 variable.After getting the URL in the text, it replaces it
2 min read
How to replace a character at a particular index in JavaScript ?
To replace a character from a string there are popular methods available, the two most popular methods we are going to describe in this article. The first method is by using the substr() method. And in the second method, we will convert the string to an array and replace the character at the index. Both methods are described below: Approach 1: Usin
4 min read
How to replace the entire HTML node using JavaScript ?
Given an HTML document and the job is to replace the entire HTML element by a new one with the help of JavaScript. A few approaches are discussed here. Approach 1: Take the new document as a form of string(eg.. Str = '< html > < /html > '). Use .replace() method on HTML element and replace it with the new HTML Document(eg.. $('html').ht
3 min read
JavaScript Symbol replace Property
JavaScript Symbol replace the property is used to determine the method that replaces the matched substring of a string. This function is called by the String replace() method. Syntax: [Symbol.replace](string) Parameters: It accepts single parameter "String". Return value: It will return a new string. The below examples illustrate the Symbol.replace
2 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
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 a JavaScript Alert Pop Up with a Fancy Alert Box ?
JavaScript alert popups are simple and effective for displaying messages to users, but they lack customization and can be visually unappealing. Below are the approaches to replace a JavaScript alert pop-up with a fancy alert box. Table of Content By overriding the alert functionUsing a SweetAlert LibraryBy overriding the alert functionIn this appro
3 min read
How to Replace a JavaScript Alert Pop up with a fancy Alert Box ?
JavaScript alert popups are an easy and effective way to show users messages, but they are not very customizable and don't always look good. Several methods exists in JavaScript to replace a JavaScript alert pop-up with a fancy alert box which are as follows: Table of Content Using Custom HTML and CSSUsing a SweetAlert LibraryUsing CSS FrameworksUs
3 min read