How to replace string in Java Script?

Introduction:

In this article i will explain how to replace string in C#.

Description:

In previous articles i explained How to replace string in SQL Server and How to replace string in C#. Now i will explain how to replace string in Java Script. And how many ways we can replace the string in Java Script.

Example:

var oText = 'Hi sagar reddy';
var nText = oText.replace('sagar', 'vikram');

Output:

Hi vikram reddy

Now we will see more examples on this.

Example: (1)

var oText = 'asdAsdasd';
var nText = oText.replace('a', 'c');

Now it replaces the first occurance only.

Output:

csdasdasd

Example: (2)

Perform a global replacement:

var oText = 'asdAsdasd';
var nText = oText(/a/g, 'c');

Now it will replaces all the a's with c's.

Output:

csdAsdcsd

Example: (3)

Perform a global, case-insensitive replacement:

var oText = 'asdAsdasd';
var nText = oText.replace(/a/gi, 'c');

Output:

csdcsdcsd