//供使用者調用
function trim(s){
return trimRight(trimLeft(s));
}
//去掉左邊的空白
function trimLeft(s){
if(s == null) {
return "";
}
var whitespace = new String(" \t\n\r");
var str = new String(s);
if (whitespace.indexOf(str.charAt(0)) != -1) {
var j=0, i = str.length;
while (j < i && whitespace.indexOf(str.charAt(j)) != -1){
j++;
}
str = str.substring(j, i);
}
return str;
}
//去掉右邊的空白
function trimRight(s){
if(s == null) return "";
var whitespace = new String(" \t\n\r");
var str = new String(s);
if (whitespace.indexOf(str.charAt(str.length-1)) != -1){
var i = str.length - 1;
while (i >= 0 && whitespace.indexOf(str.charAt(i)) != -1){
i--;
}
str = str.substring(0, i+1);
}
return str;
}
使用時只需調用trim函數便可。
下面是用正則的實現方法:
<SCRIPT LANGUAGE="JavaScript"> <!-- 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, ""); } //--> </SCRIPT> <input type="text" value=" 先後都是空格 " id="space"> <input type="button" value="去先後空格" onclick="javascript:document.getElementById('space').value=document.getElementById('space').value.Trim();document.getElementById('space').select();"> <input type="button" value="去前空格" onclick="javascript:document.getElementById('space').value=document.getElementById('space').value.LTrim();document.getElementById('space').select();"> <input type="button" value="去後空格" onclick="javascript:document.getElementById('space').value=document.getElementById('space').value.RTrim();document.getElementById('space').select();"> <input type="button" value="還原" onclick="javascript:document.getElementById('space').value=' 先後都是空格 ';">