Remove whitespace From String using jQuery

Remove whitespace From String

Overview

How to remove all whitespace or unwanted whitespace from a string in jquery?

In this article, we will learn how to remove all white space or unwanted whitespace 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>  

Check This Also

Difference between AngularJS and Angular 2 Make a Mobile app in just 10 minutes With Ionic Framework Angular 9: What to Expect in New Version of Angular Alert (Toaster) Notifications in Angular 8