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: 15-Jun-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements