How to remove white spaces from a strings in jQuery

Topic: JavaScript / jQuery« Prev|Next »

Answer: Use the jQuery $.trim() function

You can use the 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 occurs 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-1.12.4.min.js"></script>
  • <script type="text/javascript">
  •     $(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>

Related FAQ

Here are some more FAQ related to this topic:

 
Close

Your Feedback:

 

We would love to hear from you! Please say something.