jQuery trim() function example

jQuery trim() function is used to remove the whitespace from the beginning and end of a string.

Syntax

jQuery.trim( str )
str - The string to trim.

Example

Remove the white spaces at the start and at the end of the string.
<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>jQuery.trim demo</title>
    <script src="https://code.jquery.com/jquery-3.4.1.js"></script>
</head>

<body>

    <pre id="original"></pre>
    <pre id="trimmed"></pre>

    <script>
        var str = "         lots of spaces before and after         ";
        $("#original").html("Original String: '" + str + "'");
        $("#trimmed").html("$.trim()'ed: '" + $.trim(str) + "'");
    </script>

</body>

</html>
Output:
Original String: '         lots of spaces before and after         '
$.trim()'ed: 'lots of spaces before and after'
Try it Yourself - Copy paste code in Online HTML Editor to see the result

Comments