How to Replace String in JavaScript?

Share Me
  •  
  •  
  •  
  • 2
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    2
    Shares
How to Replace String in JavaScript

Today in this tutorial, i will give you a short and simple example of how to replace string by using javascript. We can easily replace all string by using javaScript method. Here i will explain the javascript string.replace() method also with the definition of this method, syntax, parameters, and also several examples. Here we see How to Replace String in JavaScript.

Now the JavaScript string replace() method is searches a string for a specified value or a regular expression, or keyword, and replace match search string to given string, returns with the new string.

Syntax
string.replace(search_value, new_value);

Parameter Values

search_value :-

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

new_value :-

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

Here i can blow you can easily replace string by using javascript in this example.

Example Repalce Word

Also here the contents of the string coding will be replaced with point, In this example single string replace.

<!DOCTYPE html>
<html>
<head>
	<title>Replace String Using JavaScript - https://www.codingspoint.com/</title>
</head>
<body>
    <p>Click the button to replace "coding" with "point" in the paragraph below:</p>

    <p id="demo">Visit coding!</p>

    <button onclick="myFunction()">Click Here</button>

    <script>
    function myFunction() {
      var str = document.getElementById("demo").innerHTML; 
      var res = str.replace("coding", "point");
      document.getElementById("demo").innerHTML = res;
    }
     </script>
</body>
</html>
Example Repalce All Word

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

<!DOCTYPE html>
<html>
<head>
	<title>Repalce All String Using JavaScript - https://www.codingspoint.com/</title>
</head>
<body>
    <p>Click the button to replace "red" with "green" in the paragraph below:</p>

    <p id="demo">Mr Green has a red 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(/red/gi, "green");
      document.getElementById("demo").innerHTML = res;
    }
    </script>
</body>
</html>

Read Also : Add Charts Using Highcharts In Laravel 8

Thanks for read. I hope it help you. For more you can follow us on facebook.

About code chef

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by code chef →