jQuery Remove Whitespace From String

JQuery remove all whitespace from string; Through this tutorial, i am going to show you how to remove all whitespace or unwanted whitespace from the given string in jquery.

Sometimes users can enter whitespaces in the text box, input box, and you want to remove that spaces before storing string, text into the database.

How to remove all whitespace from string in JQuery

There are two functions of jquery which is trim() and replace; This functions are used to remove all whitespaces and unwanted whitespaces from given string.

  • jQuery remove unwanted whitespace from string
  • jQuery remove all whitespace from string

jQuery remove unwanted whitespace from string

See the following example for how to remove all whitespaces from a string of text using jQuery trim(); as shown below:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Remove All White Spaces from a Strings</title>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>   
<script type="text/javascript">
    $(function () {
        $('#test').keyup(function () {                     
            var text = $.trim($(this).val());
            $(".trimmed").html(text);
        });
    }); 
</script>
</head>
<body>
    <h3>Original String</h3>
    <input id="test" type="text" />
    <br>
    <h3>Trimmed String</h3>
    <pre class="trimmed"></pre>
</body>
</html>                            

Demo for jQuery remove unwanted whitespace from string


Remove All White Spaces from a Strings

Original String


Trimmed String





jQuery remove all whitespace from string

See the following example for how to remove all whitespaces from a string of text using jQuery replace(); as shown below:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Remove All White Spaces from a Strings</title>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>   
<script type="text/javascript">
    $(function () {
        $('#test1').keyup(function () {                     
            var text = $(this).val();
            console.log(text);
            var newMyText = text.replace(/ /g,'');
            $("#trimmed").html(newMyText);
        });
    }); 
</script>
</head>
<body>
    <h3>Original String</h3>
    <input id="test1" type="text" />
    <br>
    <h3>Trimmed String</h3>
    <pre id="trimmed"></pre>
</body>
</html>                            

Demo for jQuery remove all whitespace from string


Remove All White Spaces from a Strings

Original String


Trimmed String





Recommended jQuery Tutorials

Leave a Comment