jQuery to replace all spaces with underscores while typing in textbox

Introduction: In this article I am going to share how to replace or convert all spaces into underscores while typing in asp.net textbox or multiline textbox.

jQuery to replace all spaces with underscores while typing in textbox

Description: Sometime we want to restrict user to enter spaces in between text by replacing the space entered with underscore as shown in image above. This can be done easily using jquery. I have mentioned two ways to get this requirement done. You can use any on these two.

First way:
            $('#<%=txtData.ClientID%>').keyup(function () {
                this.value = this.value.replace(/ /g, "_");

Second way:
            $('#<%=txtData.ClientID%>').keyup(function () {
                $(this).val($(this).val().split(' ').join('_'));

Implementation: Let’s create a demo page for demonstration purpose.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $('#<%=txtData.ClientID%>').keyup(function () {
                this.value = this.value.replace(/ /g, "_");            
    <form id="form1" runat="server">
            <fieldset style="height: 40px; width: 350px;">
                <legend>Replace all spaces with undersore while typing</legend>
                <asp:TextBox ID="txtData" runat="server" style="width:350px;"></asp:TextBox>

Now over to you:
"A blog is nothing without reader's feedback and comments. So please provide your valuable feedback so that i can make this blog better and If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linkedin and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned and stay connected for more technical updates."
Next Post »


Click here for comments
Kapil Vyas
October 15, 2015 ×

Nice Article. Thankx and Keep Posting

October 17, 2015 ×

Thanks kapil for your feedback. Its always nice to hear my articles helped anyone. Stay connected and keep reading for more useful updates on bootstrap and other.


If you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily..