jQuery Remove White Spaces From A String Example

Overview

How to remove all white spaces from a string in jquery? In this article, you will learn how to remove all white spaces from the given string.

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

jQuery $.trim() function to remove all spaces (including non-breaking spaces), newlines, and tabs from the beginning and end of the specified string. However, the whitespaces that occur in the middle of the string are preserved.

Let’s take Example

The following example will show you how to remove leading and trailing whitespaces from a string of text.

<!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>                            

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *