当前位置: 首页 > 图文教程 > 网络编程 > Javascript > js中几种去掉字串左右空格的方法

Javascript
form中限制文本字节数js代码
use jscript with List Proxy Server Information
use jscript List Installed Software
List Installed Software Features
List Information About the Binary Files Used by an Application
List the Codec Files on a Computer
List the UTC Time on a Computer
List Installed Hot Fixes
excel操作之Add Data to a Spreadsheet Cell
Add Formatted Data to a Spreadsheet
Apply an AutoFormat to an Excel Spreadsheet
JavaScript语法着色引擎(demo及打包文件下载)
类之Prototype.js学习
一款JavaScript压缩工具:X2JSCompactor
iis6+javascript Add an Extension File
jscript之Open an Excel Spreadsheet
jscript之Read an Excel Spreadsheet
jscript之List Excel Color Values
去除图像或链接黑眼圈的两种方法总结
Add a Formatted Table to a Word Document

Javascript 中的 js中几种去掉字串左右空格的方法


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-12   浏览: 186 ::
收藏到网摘: n/a

//recon 的思路:
//-------------
//去掉字串左边的空格
function ltrim(str)
{
if (str.charat(0) == " ")
{
//如果字串左边第一个字符为空格
str = str.slice(1);//将空格从字串中去掉
//这一句也可改成 str = str.substring(1, str.length);
str = ltrim(str); //递归调用
}
return str;
}
//去掉字串右边的空格
function rtrim(str)
{
var ilength;
ilength = str.length;
if (str.charat(ilength - 1) == " ")
{
//如果字串右边第一个字符为空格
str = str.slice(0, ilength - 1);//将空格从字串中去掉
//这一句也可改成 str = str.substring(0, ilength - 1);
str = rtrim(str); //递归调用
}
return str;
}
//去掉字串两边的空格
function trim(str)
{
return ltrim(rtrim(str));
}
//雨天5337 的思路:
//----------------
function alltrim(a_strvarcontent)
{
var pos1, pos2, newstring;
pos1 = 0;
pos2 = 0;
newstring = ""
if ( a_strvarcontent.length > 0 )
{
for( i=0; i<=a_strvarcontent.length; i++)
//recon: 这句应该有错误,应改成:
//for( i=0; i<a_strvarcontent.length; i++)
{
if ( a_strvarcontent.charat(i) == " " )
pos1 = pos1 + 1;
else
break;
}
for( i=a_strvarcontent.length; i>=0 ; i--)
//recon: 这句应该有错误,应改成:
//for( i=a_strvarcontent.length-1; i>=0 ; i--)
{
if ( a_strvarcontent.charat(i) == " " )
pos2 = pos2 + 1;
else
break;
}
newstring = a_strvarcontent.substring(pos1, a_strvarcontent.length-pos2)
}
return newstring;
}
//hooke 的思路:
//-------------
function jtrim(sstr)
{
var astr="";
var dstr="";
var flag=0;
for (i=0;i<sstr.length;i++)
{if ((sstr.charat(i)!=' ')||(flag!=0))
{dstr+=sstr.charat(i);
flag=1;
}
}
flag=0;
for (i=dstr.length-1;i>=0;i--)
{if ((dstr.charat(i)!=' ')||(flag!=0))
{astr+=dstr.charat(i);
flag=1;
}
}
dstr="";
for (i=astr.length-1;i>=0;i--) dstr+=astr.charat(i);
return dstr;
}
为什么不用正则表达式?
String.prototype.Trim = function()
{
return this.replace(/(^\s*)|(\s*$)/g, "");
}