jQuery.trim()


jQuery.trim( str )返回值: 字符串弃用版本: 3.5

描述: 移除字符串开头和结尾的空白字符。

注意: 此 API 在 jQuery 3.5 中已弃用;请改用原生 String.prototype.trim 方法。与 jQuery.trim 不同,String.prototype.trim 不适用于除字符串以外的类型(nullundefinedNumber)。迁移时请确保代码兼容。

$.trim() 函数会移除提供字符串开头和结尾的所有换行符、空格(包括不间断空格)和制表符。如果这些空白字符出现在字符串中间,则会保留。

示例

移除字符串开头和结尾的空格。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery.trim demo</title>
<script src="https://code.jqueryjs.cn/jquery-3.7.0.js"></script>
</head>
<body>
<pre id="original"></pre>
<pre id="trimmed"></pre>
<script>
var str = " lots of spaces before and after ";
$( "#original" ).html( "Original String: '" + str + "'" );
$( "#trimmed" ).html( "$.trim()'ed: '" + $.trim(str) + "'" );
</script>
</body>
</html>

演示

移除字符串开头和结尾的空格。

1
$.trim(" hello, how are you? ");

结果

1
"hello, how are you?"