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');

  }

});

Tags:

C# DateTime ToString().net String vs stringAsp.net Convert String To Image[C#] Remove Last Character From StringReplace string in C#DateTime format Time StringSplit String In C#Linq Convert String Array To Int ArrayHow to Pass To Query String In Asp.netHow To Declare and access array of string in C#C# foreach loop

Author

My name is Satalaj, but people call me Sat. Here is my homepage: . I live in Pune, PN and work as a Software Engineer. I'm former MVP in ASP.net year 2010.
Disclaimer: Views or opinion expressed here are my personal research and it has nothing to do with my employer. You are free to use the code, ideas/hints in your projects. However, you should not copy and paste my original content to other web sites. Feel free to copy or extend the code.
If you want to fight with me, this website is not for you.
 

I'm Satalaj.