JS去掉中间左右空格Javascript
1、
js实现TRIM功能
<SCRIPT LANGUAGE="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, "");
}
</SCRIPT>
str = str.replace(/[ ]/g,""); //替换所有空格
str.replace(/(^\s*)|(\s*$)/g, ""); //去掉左右空格
str.replace(/(\s*$)/g, ""); //去掉右空格
str.replace(/(^\s*)/g, ""); //去掉左空格
2、
//去除字符串两边空格的函数
//参数:mystr传入的字符串
//返回:字符串mystr
function trim(mystr){
while ((mystr.indexOf(" ")==0) && (mystr.length>1)){
mystr=mystr.substring(1,mystr.length);
}//去除前面空格
while ((mystr.lastIndexOf(" ")==mystr.length-1)&&(mystr.length>1)){
mystr=mystr.substring(0,mystr.length-1);
}//去除后面空格
if (mystr==" "){
mystr="";
}
return mystr;
}
str = str.replace(/[ ]/g,""); //替换所有空白
//刪除所有空白
function allTrim(s)
{
var s1 = lTrim(s);
return (rTrim(s1));
}
//刪除左方空白(含全形空白)
function lTrim(s)
{
s = "" + s;
var len = s.length;
var pos = 0;
var s1 = "";
while (pos < len)
{
var chr = s.substring(pos, pos + 1);
if (chr == " " || chr == "" || chr == " ")
pos = pos + 1;
else
return (s.substring(pos,len));
}
return s1;
}
//刪除右方空白(含全形空白)
function rTrim(s)
{
s = "" + s;
var len = s.length;
var pos = len -1;
var s1 = "";
var i = 0;
while (pos >= 0)
{
var chr = s.substring(pos, s.length - i);
if (chr == " " || chr == "" || chr == " ")
pos = pos - 1;
else
return (s.substring(0, pos +1));
i++;
}
return s1;
}
//去掉字符串中間多餘空白(保留一個空白)
function middleTrim(str)
{
var repStr="";
for(var i=0;i<str.length;i++)
{
if(str.substring(i,i+1)!=" ")
repStr=repStr+str.substring(i,i+1);
else
{
if(repStr.substring(repStr.length-1,repStr.length)!=" ")
{
repStr=repStr+" ";
}
}
}
return repStr;
}