为javascript中String扩展的几个方法

每次在javascript中用加号合成字符串,真的没法忍受了,今天终于找到一高手写的方法,与大家分享。
1、为javascript添加String.Format方法

String.format = function()
{

    
if( arguments.length == 0 )
    {
        
return null
    }
    
    
var str = arguments[0]; 

    
for(var i=1;i<arguments.length;i++)
    {

        
var re = new RegExp('\\{' + (i-1+ '\\}','gm');
        str 
= str.replace(re, arguments[i]);
    }
    
return str;
}

使用方式 : String.format('Hello. My name is {0} {1}.', firstName, lastName);

 

2、去算字符串空间的相关扩展方法:

/**
*删除左右两端的空格
*/
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,'');
}

 

使用方法:

alert(document.getElementById('abc').value.trim());
alert(document.getElementById('abc').value.ltrim());
alert(document.getElementById('abc').value.rtrim());

 

 

posted on 2009-11-09 12:14  凡夫·俗子  阅读(650)  评论(0编辑  收藏  举报