Replace a Word from everywhere in a String using JavaScript

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.

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.

Change font-size using JavaScript Get Font Size of any Tag using JavaScript Change Position of HTML Element using JavaScript How to Change Image on Hover with JavaScript How to Disable Button by Class Name in JavaScript How To Change Image Size with JavaScript How to change Image opacity with JavaScript How to Change image src on click with JavaScript How to get the lang attribute value in JavaScript How to Get attribute Value using JavaScript How To Check if Attribute Exists or not with JavaScript How To Count number of links on Page with JavaScript How To Scroll Page to Bottom using JavaScript How To Detect Shift Key Press with JavaScript Change Text Color On Hover with JavaScript Hide and Show div using JavaScript Get Button text with JavaScript Get textarea value with JavaScript Get table row Height with JavaScript Auto Increase width of input field with JavaScript Set Textarea maxLength with JavaScript Set Textarea Value with JavaScript JavaScript Count list items JavaScript set input field value Count Button Clicks with JavaScript Scroll Page to the Top on Click with JavaScript