在處理表單輸入時,使用者常會不小心多打了空格,這時就需要去除字串前後的空白。JavaScript 可以透過正則表達式為 String 擴充 Trim、LTrim、RTrim 三個方法,分別去除兩側、左側與右側空格。
效果體驗:https:///keleyi/phtml/javascript/1.htm
完整代碼如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>測試去空格-</title>
<script type="text/javascript">
//Trim() , Ltrim() , RTrim() 函數
String.prototype.Trim = function()
{
return this.replace(/(^\s*)|(\s*$)/g, '');
}
String.prototype.LTrim = function()
{
return this.replace(/(^\s*)/g, "");
}
String.prototype.RTrim = function()
{
return this.replace(/(\s*$)/g, "");
}
function testTrim()
{
var name;
name = document.keleyiform.uname.value.Trim();
//name = document.keleyiform.uname.value.RTrim();
//name = document.keleyiform.uname.value.LTrim();
if (name.length == 0) {
alert("用戶明不能為空!" + name.length);
document.myform.uname.select();
return false;
}
else {
alert(name.length);
}
}
</script>
</head>
<body>
<form id="keleyiform" name="keleyiform" method="get" action="">
<label>
<input type="text" name="uname" />
</label>
<label>
<input type="submit" name="Submit" value="提交" onclick="return testTrim()" />
</label>
</form>
</body>
</html>
其中三個正則的含義分別是:/(^\s*)|(\s*$)/g 匹配開頭或結尾的空白(兩側),/(^\s*)/g 只匹配開頭(左側),/(\s*$)/g 只匹配結尾(右側)。值得一提的是,現代瀏覽器已原生支援 String.prototype.trim(),但在需要兼容舊環境或自訂左右去空格時,這種擴充方法仍然很實用。