JavaScript | string.replace()
The string.replace() is an inbuilt function 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.
Code #1:
Here the contents of the string GeeksForGeeks will be replaced with gfg.
<script> // Assigning a string var string = 'GeeksForGeeks is a CS portal' ; // Calling replace() function var newstring = string.replace(/GeeksForGeeks/, 'gfg' ); // Printing replaced string document.write(newstring); </script> |
Output:
gfg is a CS portal
Code #2:
<script> // Taking a regular expression var re = /GeeksForGeeks/; // Taking a string as input var string = 'GeeksForGeeks is a CS portal' ; // Calling replace() function 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
Recommended Posts:
- Introduction to JavaScript Course | Learn how to Build a task tracker using JavaScript
- How to compare two JavaScript array objects using jQuery/JavaScript ?
- JavaScript Course | Understanding Code Structure in JavaScript
- JavaScript Course | Conditional Operator in JavaScript
- JavaScript Course | Logical Operators in JavaScript
- JavaScript Course | Printing Hello World in JavaScript
- JavaScript Course | Data Types in JavaScript
- JavaScript Course | Variables in JavaScript
- JavaScript Course | Functions in JavaScript
- JavaScript Course | Loops in JavaScript
- JavaScript Course | Operators in JavaScript
- JavaScript Course | JavaScript Prompt Example
- JavaScript Course | Objects in JavaScript
- JavaScript vs Python : Can Python Overtop JavaScript by 2020?
- How to include a JavaScript file in another JavaScript file ?
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.