c# .net Adsense ADO.NET Linq Viruses/security asp.net MVC JQuery Angular-js Node-js SEO Java C++ SQL API Networking vb.net .Net Css JavaScript Generics c#.Net entity framework HTML Website host Website Construction Guide HTTP tutorial W3C tutorial Web Services JSON Psychology Ionic framework Angular ReactJS Python Computer Android
JavaScript

How to replace strings in JavaScript?

| | Html , JavaScript

In this article we will discuss to replace strings in JavaScript by using replace() method. It searches a given specified string and replaces with the replacement values.

For example:

If we want to replace tutorials with techniques

<script type="text/javascript">

    var myString = "infinetsofttutorials";

    var result = myString.replace("tutorials", "techniques");

    alert(result);

  </script>

 

Output:

Replace string with case sensitive:

A regular expression between 2 forward slashes(//) and letter g after last forward slash. This is case sensitive below example describes about it.

<script type="text/javascript">

    var myString = "A Black pen is on the black table.";

    var result = myString.replace(/black/g, "white");

    alert(result);
</script>
 

Output:

Replace string with case insensitive:

Same as that of case sensitive instead of g after the forward slash here we are using gi. The is case insensitive.

<script type="text/javascript">

    var myString = "ABlack pen is on the black table.";

    var result = myString.replace(/black/gi, "red");

    alert(result);

  </script>

 

Output: