3 Example(s) of JavaScript replace function
Description :
JavaScript replace()
function replace the string provided with new value. See the code snippet:
JavaScript replace function Example - 1
<!DOCTYPE html>
<html>
<head>
<title>Welcome to LearnKode - A code learning platform</title>
</head>
<body>
<p id="sample">Visit Google!</p>
<button onclick="newString()">Replace string</button>
<script>
function newString() {
var str = document.getElementById("sample").innerHTML;
var result = str.replace("Google", "LearnKode");
document.getElementById("sample").innerHTML = result;
}
</script>
</body>
</html>
Description :
With the help of JavaScript replace function
, It will replace the string like with love.. Here is the syntax
str.replace(/like/g, "love");
JavaScript replace function Example - 2
<html>
<head>
<title>Welcome to LearnKode - A code learning platform</title>
</head>
<body>
<button onclick="newString()">Replace string</button>
<p id="sample">I like Learnkode</p>
<script>
function newString() {
var str = document.getElementById("sample").innerHTML;
var result = str.replace(/like/g, "love");
document.getElementById("sample").innerHTML = result;
}
</script>
</body>
</html>
Description :
Example of replace with regex expression
:
JavaScript replace function Example - 3
<!DOCTYPE html>
<html>
<head>
<title>Welcome to LearnKode - A code learning platform</title>
</head>
<body>
<script>
var regexp = /(\w+)\s(\w+)/;
var str = 'Michael Voughan';
var result= str.replace(regexp , '$2, $1');
document.write(result)
</script>
</body>
</html>