JavaScript String method : replace()

The replace() method is used to replace a specified value with another value in a string. It basically does not replace the value on original string but stores the new modified string into new variable. It also only replace the first match. The basic syntax is as follows :
  var newStr = str.replace(old_value, new_value);
Where old_value represent the value which will be replaced and the new_value represents the value to replaced.

Example :
<html>
<body>
  <script>
    var str = "Wakanda is a good country.";
    var newStr = str.replace('good', 'best'); 
    document.write(newStr);
  </script> 
</body>
</html>
Output :


by-default replace() method is case sensitive, to disable case sensitivity we need to add an /i flag, For example :
  var newStr = str.replace(/old_value/i, new_value);
Example :
<html>
<body>
  <script>
    var str = "Wakanda is a Good country.";
    var newStr = str.replace(/good/i, 'Best'); 
    document.write(newStr);
  </script> 
</body>
</html>
Output :



Next Topic :