How to replace string in JQuery?

Introduction:

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

Description:

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

Syntax:

In JQuery we will use replace(regExp, replcaement) method to replace substring. See the following examples:

Example: (1)

var oText = 'vikramreddy@gmail.com', nText = '';

Now we will replace the mail from @gmail.com to @studentboxoffice.in.

nText = oText.replace('@gmail.com', '@studentboxoffice.in');

Output:

vikramreddy@studentboxoffice.in

Example: (2)

var oText = 'asdAsdasd', nText = '';

Now we will replace a with c.

nText = oText.replace(/a/g, 'c');

Output:

csdAsdcsd

Note: In output A is not replaced because it is case-sensitive. To replace all a's with c then use /gi instead of /g. Means global case-insensitive.


Full Source Code:

ReplaceStringInJquery.aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ReplaceStringInJquery.aspx.cs"
    Inherits="UI.ReplaceStringInJquery" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Replace string in jQuery</title>
    <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.1.js"></script>
    <script type="text/javascript">
        var oText = 'vikramreddy@gmail.com', nText = '';
        $(document).ready(function ()
        {
            $('#btnReplace').click(function ()
            {
                $('#spnOldEmail').text(oText);
                //replace(regExp, replcaement)
                nText = oText.replace('@gmail.com', '@studentboxoffice.in');
                $('#spnNewEmail').text(nText);
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <table>
        <tr>
            <td>Old Email: 
            </td>
            <td><span id="spnOldEmail"></span>
            </td>
        </tr>
        <tr>
            <td colspan="2">
        <input type="button" id="btnReplace" value="Replace" />
            </td>
        </tr>
        <tr>
            <td>New Email: 
            </td>
            <td>
                <span id="spnNewEmail"></span>
            </td>
        </tr>
    </table>
    </form>
</body>
</html>

Output: