Q:

How to remove white spaces from a string in jQuery

0

How to remove white spaces from a string in jQuery

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Use the jQuery $.trim() function

You can use the jQuery $.trim() function to remove all the spaces (including non-breaking spaces), newlines, and tabs from the beginning and end of the specified string.

However, the whitespaces in the middle of the string are preserved. 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 White Space from Strings</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
    $(document).ready(function(){
        var myStr = $(".original").text();
        var trimStr = $.trim(myStr);
        $(".trimmed").html(trimStr);
    });
</script>
</head>
<body>
    <h3>Original String</h3>
    <pre class="original">      Paragraph of text with       multiple    white   spaces before and after.       </pre>
    <br>
    <h3>Trimmed String</h3>
    <pre class="trimmed"></pre>
</body>
</html>

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to find the number of characters in a string u... >>
<< How to remove elements from DOM in jQuery...