Jquery Trim String

Jquery Trim String

How to use the JQuery trim() function?

 

How to trim a string using Jquery.trim()/ jquery trim function? 

In our daily client side script programming tasks we come across situations where we need to trim leading and trailing space of strings. To achieve this objective more consistently is much easier in jquery that using pure javascript.

If these whitespace characters occur in the middle of the string, they are preserved.

JQuery.trim() Returns: String

This works perfectly on all availabe modern browsers! :)

 We need to include below script in order to use this jquery trim function.

<script src="http://code.jquery.com/jquery-latest.js"></script>

Below is Jquery string trim (Jquery trim string) example using Jquery.trim()

Code

<!DOCTYPE html>

<html>

<head>

  <script src="http://code.jquery.com/jquery-latest.js"></script>

</head>

<body>

  <button>Click to Trim string</button>

<script type="'text/javascript">

$("button").click(function () {

var mystring = "     There are lots of spaces at the start (Leading) and end (Trailing) of this text    ";

alert("'" + mystring + "'");

mystring = jQuery.trim(mystring);

alert("'" + mystring + "' – Leading and Trailing spaces have now been removed");

});

</script>

</body>

</html>

This will trim the extra white spaces before and after the sentence and alert the resulting string.

The trim method can also be used to check/determine whether element is empty string

Code

$(document).ready(function() {

  if ($('#MyDIV').html().trim()) {

    alert('Element contains some text! NOT EMPTY');

  }

  else

  {

    alert('Element is EMPTY, nothing in it');

  }

});

Currently rated 3.0 by 10 people

  • Currently 3/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5