Skip to content
Related Articles

Related Articles

JavaScript string.replace() Method

View Discussion
Improve Article
Save Article
  • Difficulty Level : Basic
  • Last Updated : 06 Oct, 2021

Below is the example of the string.replace() Method. 
 

  • Example: 
     

javascript




<script>
    var string = 'GeeksForGeeks';
    var newstring = string.replace(/GeeksForGeeks/, 'GfG');
 
    document.write(newstring);
</script>

  • Output: 
     
GfG

The string.replace() is an inbuilt method in JavaScript which is used to replace a part of the given string with some another string or a regular expression. The original string will remain unchanged.
Syntax: 
 

str.replace(A, B)

Parameters: Here the parameter A is regular expression and B is a string which will replace the content of the given string. 
Return Values: It returns a new string with replaced items.
JavaScript code to show the working of this method: 
Code #1: 
Here the contents of the string GeeksForGeeks will be replaced with gfg. 
 

javascript




<script>
 
    // Assigning a string
    var string = 'GeeksForGeeks is a CS portal';
 
// Calling replace() method
var newstring = string.replace(/GeeksForGeeks/, 'gfg');
 
// Printing replaced string
document.write(newstring);
 
</script>

Output: 
 

gfg is a CS portal

Code #2: 
 

javascript




<script>
 
    // Taking a regular expression
    var re = /GeeksForGeeks/;
 
// Taking a string as input
var string = 'GeeksForGeeks is a CS portal';
 
// Calling replace() method to replace
// GeeksForGeeks from string with gfg
var newstring = string.replace(re, 'gfg');
 
// Printing new string with replaced items
document.write(newstring);
 
</script>

Output: 
 

gfg is a CS portal

Supported Browsers: 
 

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

 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!