In this tutorial we will see how to Replace a Word from everywhere in a String using JavaScript. The JavaScript replace() method is used with RegExp g Modifier to find and replace word from string.
Table of Contents
HTML Code
HTML Code is given below, This code contains HTML input element, button element and a paragraph element.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Replace a Word from everywhere in a String using JavaScript</title>
</head>
<body>
<input id='input' type="text">
<button onclick="replace()">Replace</button>
<p id='output'></p>
</body>
</html>
JavaScript replace() Method
The JavaScript replace() Method is used to replace one string with another string.
JavaScript replace() Method checks a given string for specified word or regular expression and then returns a new string after replacing the values.
JavaScript replace() Method is supported by all major browsers.
RegExp g Modifier
RegExp g Modifier is used for the global match. To replace all occurrences of a specified value or word we can use the global modifier (g).
RegExp g Modifier is also supported by all major browsers.
JavaScript Code
In this example onclick event is used to trigger the main function. The main function will then replace the defined word 'JavaScript' from everywhere in the string with another defined word 'School'.
Take a look at the code given below.
<script>
function replace()
{
var a = document.getElementById('input').value;
var b = a.replace(/JavaScript/g, "School");
document.getElementById('output').innerHTML=b;
}
</script>
Demo
Video Tutorial
Watch video tutorial on how to Replace a Word from everywhere in a String using JavaScript.