String Replace Function with RegEx in JavaScript

JavaScriptAs you know, replace() function is used to replace value in a given string.  It also takes regex as parameter to perform the search for replacement.  With regex, you can perform 2 kinds of searches, global case-sensitive and global case-insensitive.  For global case-sensitive search, we add g at the end of regex and for global case-insensitive search, we add gi at the end of regex.  Example of both scenarios is given below.

<!DOCTYPE html>
<html>
<head>
<title>JavaScript Tutorial</title> 	
</head>
<body>
<script type="text/javascript">
	
	var myString = "Green man running on a green grass with green bag.";
	
	var sensitive = myString.replace(/green/g, "red");

	document.write(sensitive + "<br>");

	var insensitive = myString.replace(/green/gi, "red");

	document.write(insensitive);

</script>

</body>
</html>

 

  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •