Strip out space from user input using JavaScript (ReplaceAll)

While I was trying to strip out all space from user input using JavaScript, First I tried with using simple replace function like var strDest = strSrc.replace(" ",""). But, I see the result that it only replaces the first occurance of the space in source string. Intrestingly, I googled and found one solution to remove all the spaces from a string that is " / /gi" parameter. Here is the JavaScript to strip out spaces from a string/user input:

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
    <script type="text/javascript" language="javascript">
    function CheckSpace()
    {
        var strSrc = document.getElementById('<%=TextBox1.ClientID%>').value;
        //here we need to give the string/char that we need to replace from source string
        //in my case it is space for I gave a space between two forward slashes as var spaceFix = / /gi;
        //if you want to replace for example all "a" then it should be written as var spaceFix = /a/gi;
        var spaceFix = / /gi;
        var strDest = strSrc.replace(spaceFix,"");
        alert(strDest);
        return false;
    }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="return CheckSpace();" /></div>
    </form>
</body>
</html>

Comments

# Strip out space from user input using JavaScript (ReplaceAll) &laquo; KaushaL.NET

Pingback from  Strip out space from user input using JavaScript (ReplaceAll) « KaushaL.NET

# re: Strip out space from user input using JavaScript (ReplaceAll)

Tuesday, October 06, 2009 9:33 PM by Tung Nguyen

Thank you so much for your helpful information!!!!!!!!!!

# re: Strip out space from user input using JavaScript (ReplaceAll)

Thursday, November 12, 2009 2:23 PM by David

OMG THANK YOU IT WORKED!!!