Updated July 28, 2023
Introduction to Replace Function in JavaScript
JavaScript provides us with many inbuilt functions, which also include replace functions. Replace function in JavaScript is used to replace strings. It replaces a given string or some part of the string. But in this function, also original string will not change. Replace() method search for a specified value in the string or a regular expression and replace the string without modifying the original string because it always returns the new string.
Syntax
Below is the syntax:
string.replace(A, B)
This replace method takes two parameters; let’s discuss them in detail:
Parameters:
- It has two parameters as, A and B.
- A parameter is a regular expression, and another parameter which is B, will be a string that is responsible for replacing the content from the given string.
or
var newString = str.replace(reg-expression|str, newSubstr|functionTocall)
Here we will discuss the below syntax in detail.
- function (replacement): This is used to call a function responsible for creating a new substring which in turn is used to replace the content matched in the original string.
- newSubStr (replacement): This is used to replace the substring’s content specified by the regular expression or string value itself.
- regexp (pattern): This is used to replace; basically, it matches the pattern with the string and replaces it with a new substring.
- substr (pattern): This would be the string that will be replaced by new content. In this, only the first occurrence will be replaced.
- Return value: This method returns the new string object without modifying the original string. So it will provide us with the changed string with replaced content.
We can also say this variable is a search value and a new value. Both these parameters are required; they are not optional. It uses JavaScript Version, i.e., ECMAScript 1.
Example:
To show basic usage of replace() function.
Code:
<!DOCTYPE html>
<html>
<body>
<p>Prerss the bnutton to replace content "abc" with "black" in the content below </p>
<p id="demo">This abc will be reaplce by balck from abc black.</p>
<button onclick="myFunction1()">Try to press!</button>
<script>
function myFunction1() {
var str = document.getElementById("demo").innerHTML;
var res = str.replace(/abc/g, "wooooo");
document.getElementById("demo").innerHTML = res;
}
</script>
</body>
</html>
Output:
How does Replace Function Work in JavaScript?
Replace() function replaces the string as the name suggests; it replaces the whole or some string depending upon the input or pattern we pass. This pattern can be like a regular expression or a string value. But in this, we have to note one thing, i.e., if the pattern we are passing is a string value, then only the first occurrence of the string will be replaced. To replace all occurrences, we must pass a regular expression to find and replace all instances.
But in all this, our original string will still be unchanged. So basically, it does not change the string object on which it is called. It will just return the new string. If we want to perform a global replace and search, we need to include the g switch while using the regular expression.
The replacement string contains some special character patterns:
- $$: It will inserts “$”.
- $&: It will insert the matched substring.
- $’: It will insert the string portion that will match the following sun string.
- $`: This will insert the string preceding the matching substring.
- $n: Here, n is the positive integer less than 100; it will insert the nth match string. Note this is l-indexed.
While using replace() method, we can also mention this function parameter as the second parameter, but in this case, this function will be invoked only after the match with the corresponding string has been performed.
We have the following argument for function as follows:
- string: This whole string is going to examine.
- match: This is the matched substring corresponding to the pattern above, i.e., $&
- offset: In this, we will examine the offset, so the matched string offset with the original substring will examine.
Examples of Replace Function in JavaScript
Below are examples of Replace Function in JavaScript:
Example #1
Using regular expression inside replace() function.
Code:
<!DOCTYPE html>
<html>
<body>
<p>Press button to see use of replace function </p>
<p id="demo">Some text will be replaced on click...</p>
<button onclick="myFunction1()">Try to press!</button>
<script>
function myFunction1() {
var str = document.getElementById("demo").innerHTML;
var res = str.replace(/.../i, 'RED');
document.getElementById("demo").innerHTML = res;
}
</script>
</body>
</html>
Output:
Example #2
To show global replace.
Code:
<!DOCTYPE html>
<html>
<body>
<p>Press button to see use of replace function </p>
<p id="demo">Black will be replace by another word.</p>
<button onclick="myFunction1()">Try to press!</button>
<script>
function myFunction1() {
var re = /Black/gi
var str = document.getElementById("demo").innerHTML;
var res = str.replace(re, 'yellow');
document.getElementById("demo").innerHTML = res;
}
</script>
</body>
</html>
Output:
Example #3
To show switching of words by using regular expression
Code:
<!DOCTYPE html>
<html>
<body>
<p>Press button to see use of replace function </p>
<p id="demo">Words will be reverse in this example.(first two)</p>
<button onclick="myFunction1()">Try to press!</button>
<script>
function myFunction1() {
var re = /(\w+)\s(\w+)/;
var str = document.getElementById("demo").innerHTML;
var res = str.replace(re, '$2, $1');
document.getElementById("demo").innerHTML = res;
}
</script>
</body>
</html>
Output:
Example #4
We are calling functions to perform changes and converting a string to uppercase.
Code:
<!DOCTYPE html>
<html>
<body>
<p>By clicking the button below word will be in upper case</p>
<p id="demo">Here we are chnaging some words to uppercase by clicking the button.</p>
<button onclick="myFunction1()">Try press!</button>
<script>
function myFunction1() {
var str = document.getElementById("demo").innerHTML;
var res = str.replace(/are|uppercase|button/gi, function (x) {
return x.toUpperCase();
});
document.getElementById("demo").innerHTML = res;
}
</script>
</body>
</html>
Output:
Conclusion
The JavaScript replace() function replaces the string or substring, bypassing the string as a value or regular expression. We can also call functions from inside to perform more changes on the string, like uppercase, lowercase, etc. The main advantage of using this replace function is that it never changes our original string. It will always return us a new string.
Recommended Articles
This is a guide to Replace Function in JavaScript. Here we discuss how replace function works in JavaScript? and examples. You may also have a look at the following articles to learn more –