js 去空格函数与正则

时间:2021-11-28 17:01:26
如果项目没有用到jQuery等框架的话,js本身又没有这样的函数,我们不得不自己写这样的函数,下面是函数的具体实现:

//供使用者调用
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;
}
<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=' 前后都是空格 ';">