javascript,jQuery,trim()

时间:2023-03-09 22:05:12
javascript,jQuery,trim()

JavaScript trim()

Syntax

string.trim()
  • The trim() method removes whitespace from both sides of a string.
  • The trim() method does not change the original string.

Example1

 var str = "       Hello World!        ";
alert(str.trim());

Example2

 function myTrim(x) {
return x.replace(/^\s+|\s+$/gm,'');
} function myFunction() {
var str = myTrim(" Hello World! ");
alert(str);
}

jQuery.trim()

  • Remove the whitespace from the beginning and end of a string.

Syntax

jQuery.trim( str )

Example

 <script>
var str = " lots of spaces before and after ";
$( "#original" ).html( "Original String: '" + str + "'" );
$( "#trimmed" ).html( "$.trim()'ed: '" + $.trim(str) + "'" );
</script>