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 is given below, This code contains HTML input element, button element and a paragraph element.

<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8">
<title>Replace a Word from everywhere in a String using JavaScript</title>
<input id='input' type="text">
<button onclick="replace()">Replace</button>
<p id='output'></p>

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.

 function replace()
 var a = document.getElementById('input').value;
 var b = a.replace(/JavaScript/g, "School");


Video Tutorial

Watch video tutorial on how to Replace a Word from everywhere in a String using JavaScript.

Password Show Hide with Eye Icon using JavaScript Change Background Color using Dropdown menu with JavaScript Get Select Tag value onchange in JavaScript Check If Class Exists JavaScript Add Event Listener To all Elements of Class JavaScript getElementsByTagName Event Listener JavaScript Change type attribute of Input Element With JavaScript Password Hide and Show with Toggle Emoji Button using JavaScript Hide and Show Navbar On Scroll With JavaScript Empty an Array in JavaScript Get Last Element Of Array Without Removing It Remove Last Element From Array JavaScript Remove First Element From Array in JavaScript Tic Tac Toe Game in JavaScript Remove Class from HTML Tag OnClick JavaScript JavaScript Select li Tag By Index Display JavaScript Variable In HTML Insert HTML Code anywhere With JavaScript JavaScript Date Difference in Days JavaScript Hide Button After Click Simple Click and Hold Effect Using JavaScript Remove Class From All Elements in JavaScript JavaScript Select All HTML Elements Whose ID Start With Same String