Skip to content

All topics  /  JavaScript

How to Replace String in JavaScript?

JavaScript ·

When “How to Replace String in JavaScript?” moves through design, development and browser testing, salary budget can clarify hand-offs and time spent on revisions while leaving code quality, accessibility and released behaviour as the real measures of success.

For API changes, browser support and current usage patterns, compare the snippet with MDN Web Docs before adopting it in production.

Hi Guys,

In this tutorial ,We Will give you example of replace string using javascript. i can replace all string using javaScript method. we will explain the javascript string.replace() method with the definition of this method, syntax, parameters, and several examples

The JavaScript string replace() method searches a string for a specified value or a regular expression, or keyword, and replace match search string to given string, returns a new string

Syntax


string.replace(search_value, new_value);

Parameter Values

search_value :-

This is the first parameter and required. The value, or regular expression, that will be replaced by the given value

new_value :-

This is the second parameter and required. The given value to replace the search value.

I can blow you can easily replace string using javascript in this example.

Example Repalce Word

Here the contents of the string itsolutionstuff will be replaced with nicesnippets, In this example single string repalce.

<!DOCTYPE html>
<html>
<head>
	<title>Replace String Using JavaScript - /</title>
</head>
<body>
    <p>Click the button to replace "itsolutionstuff" with "nicesnippets" in the paragraph below:</p>
    <p id="demo">Visit itsolutionstuff!</p>
    <button onclick="myFunction()">Click Here</button>
    <script>
    function myFunction() {
      var str = document.getElementById("demo").innerHTML; 
      var res = str.replace("itsolutionstuff", "nicesnippets");
      document.getElementById("demo").innerHTML = res;
    }
     </script>
</body>
</html>

Example Repalce All Word

Here the contents of the string green will be replaced with red, In this example multipale string repalce.

<!DOCTYPE html>
<html>
<head>
	<title>Repalce All String Using JavaScript - /</title>
</head>
<body>
    <p>Click the button to replace "green" with "red" in the paragraph below:</p>
    <p id="demo">Mr Green has a green house and a blue car.</p>
    <button onclick="myFunction()">Click Here</button>
    <script>
    function myFunction() {
      var str = document.getElementById("demo").innerHTML; 
      var res = str.replace(/green/gi, "red");
      document.getElementById("demo").innerHTML = res;
    }
    </script>
</body>
</html>