2011年2月12日 星期六

實作 Javascript String trim(), startsWith() 與 endWith()

String 類別是最常用的類別,但在 javascript 中並非提供基本函式,像是 substr(), trim(), startsWith() 等,這篇文章示範如何實作 Javascript String 類別的 buildin 函式

     myVar = substr2(myVar, x, y); //Your function
    myVar = myVar.substr(x, y); //built-in function

Trim()

    String.prototype.trim = function(){return 
    (this.replace(/^[\s\xA0]+/, "").replace(/[\s\xA0]+$/, ""))}

startsWith()

    String.prototype.startsWith = function(str) 
    {return (this.match("^"+str)==str)}

endsWith()

    String.prototype.startsWith = function(str) 
    {return (this.match("^"+str)==str)}

接著就可以用 build-in 的方式,呼叫這幾個函式

    var myStr = "Earth is a beautiful planet";
    var myStr2 = myStr.trim();  
    //=="Earth is a beautiful planet";
  
    if (myStr2.startsWith("Earth")) // returns TRUE
  
    if (myStr2.endsWith("planet")) // returns TRUE
  
    if (myStr.startsWith("Earth")) 
    // returns FALSE due to the leading spaces…
      
    if (myStr.endsWith("planet")) 
    // returns FALSE due to trailing spaces…

沒有留言:

張貼留言