How to trim a string using $.trim() in jQuery?



To trim a string in jQuery, use the trim() method. It removes the spaces from starting and end of the string.

The sample string I am using has spaces −

var myStr = "  Hello World    ";

Use the trim() method, 

jQuery.trim(myStr);

The following is an example to trim a string in jQuery −

Example

Live Demo

<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function(){   $("#button1").click(function(){     var myStr = "  Hello World    ";     myStr = jQuery.trim(myStr);     alert(myStr);   }); }); </script> </head> <body> <button id="button1">Trim</button> </body> </html>
Updated on: 2020-06-15T13:44:33+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements