可以使用jQuery $.trim()函数从指定字符串的开头和结尾删除所有空格(包括非中断空格),换行符和制表符。但是,保留了在字符串中间出现的空格。以下示例将展示如何从一串文本中删除开头空格和结尾空格。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Remove White Space from Strings</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var myStr = $(".original").text();
var trimStr = $.trim(myStr);
$(".trimmed").html(trimStr);
});
</script>
</head>
<body>
<h3>Original String</h3>
<pre class="original"> Paragraph of text with
multiple white spaces before and after.
</pre>
<br>
<h3>Trimmed String</h3>
<pre class="trimmed"></pre>
</body>
</html>