黃偉榮的學習筆記

軟體的世界變化萬千,小小的我只能在這洪流奮發向上以求立足。
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

ASP與JavaScript的 String.Format 方法

Posted on 2007-08-24 09:27  黃偉榮  阅读(4216)  评论(0编辑  收藏  举报

因為習慣了C#的 String.Format 去組合字串,最近在寫ASP與JavaScript時沒有這個功能實在是有夠不方便。

不過後來發現有人貼JavaScript方法,就以此方法改成ASP的

JavaScript:

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;
}


來源Blog

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

ASP
 Function StringFormat(Source,Values,IsSQL)
        
If Source = null Or Not IsArray(Values) Then        
            StringFormat 
null
        
End If        
        
        
For i = 0 To UBound(Values)
            
If  IsSQL Then
              Source 
= Replace(Source , "{" & i & "}",Replace(Values(i),"'","''"))
            
Else
              Source 
= Replace(Source , "{" & i & "}",Values(i))
            
End IF            
        
Next  
        StringFormat 
= Source             
   
End Function

我有加上 是不是SQL 語法 替換 ' 成 二個 ' ,防止 SQL injection

使用方法 : StringFormat("Select * Form Account Where ID='{0}' AND PW='{1}'" , Array(ID,PW),true)