使用这个原则,可以给预定义的构造函数(都具有原型对象)定义附加属性。例如,如果想要能够删除字符串的前后空格(与 VBScript 的 Trim 函数类似),就可以给 String 原型对象创建自己的方法。// 增加一个名为 trim 的函数作为
// String 构造函数的原型对象的一个方法。
String.prototype.trim = function()
{
// 用正则表达式将前后空格
// 用空字符串替代。
return this.replace(/(^\s*)|(\s*$)/g, "");
}// 有空格的字符串
var s = " leading and trailing spaces ";// 显示 " leading and trailing spaces (35)"
window.alert(s + " (" + s.length + ")");// 删除前后空格
s = s.trim();
// 显示"leading and trailing spaces (27)"
window.alert(s + " (" + s.length + ")");--------------------------------------------------------------------------------
© 2000 Microsoft Corporation 版权所有。保留所有权利。使用规定。
// String 构造函数的原型对象的一个方法。
String.prototype.trim = function()
{
// 用正则表达式将前后空格
// 用空字符串替代。
return this.replace(/(^\s*)|(\s*$)/g, "");
}// 有空格的字符串
var s = " leading and trailing spaces ";// 显示 " leading and trailing spaces (35)"
window.alert(s + " (" + s.length + ")");// 删除前后空格
s = s.trim();
// 显示"leading and trailing spaces (27)"
window.alert(s + " (" + s.length + ")");--------------------------------------------------------------------------------
© 2000 Microsoft Corporation 版权所有。保留所有权利。使用规定。
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, "");
}
str = " aaaa "
str.Trim()
{
Pos_Start = -1;
for(var i=0;i<his.length;i++)
{
if(his.charAt(i)!=" ")
{
Pos_Start = i;
break;
}
}
Pos_End = -1;
for(var i=his.length-1;i>=0;i--)
{
if(his.charAt(i)!=" ")
{
Pos_End = i;
break;
}
}
Str_Return = ""
if(Pos_Start!=-1 && Pos_End!=-1)
{
for(var i=Pos_Start;i<=Pos_End;i++)
{
Str_Return = Str_Return + his.charAt(i);
}
}
if (Str_Return=="")
alert("只有空格")
// return false;
else
return true;
// return Str_Return;
}