javascript 實現php str_pad

來源:互聯網
上載者:User

標籤:func   floor   manual   class   begin   char   查看   java   fse   

* 查看php.net官方手冊

string str_pad ( string $input , int $pad_length [, string $pad_string = " " [, int $pad_type = STR_PAD_RIGHT ]] )

 

* javascript code

/** * Pad a string to a certain length with another string */var STR_PAD_LEFT = 1,STR_PAD_RIGHT = 1<<1,STR_PAD_BOTH = STR_PAD_LEFT|STR_PAD_RIGHT;function str_pad(input, pad_length, pad_string, pad_type) {    var input = typeof input === "string" ? input : String.valueOf()(input);    var i, j;    var n = pad_length - input.length;        if (n <= 0)        return input;    var s = pad_string || " ",        offset = s.length,        p = "";  // 要填充的字串(可能會重複);        switch (pad_type) {    case STR_PAD_BOTH:    var q="";        for (i = 0, j=0; 0 < n; n--, i = (i+1) % s.length, j++) {        // 先在右邊添加 後再左邊添加        if (Math.floor(j / s.length) % 2 === 0) {        q += s.charAt(i);                } else {        p += s.charAt(i);        }                }        input = p + input + q;    break;        case STR_PAD_LEFT:        for (i = 0; 0 < n; n--, i = (i+1) % s.length) {        p += s.charAt(i);        }            input = p + input;            break;                case STR_PAD_RIGHT:        default:        for (i = 0; 0 < n; n--, i = (i+1) % s.length) {        p += s.charAt(i);        }            input = input + p;    }    return input;}

  

* test

// testfunction echo(s) {console.log("\"" +s + "\"");}var $input = "Alien";echo (str_pad($input, 10));                      // produces "Alien     "echo (str_pad($input, 10, "-=", STR_PAD_LEFT));  // produces "-=-=-Alien"echo (str_pad($input, 10, "_", STR_PAD_BOTH));   // produces "__Alien___"echo (str_pad($input,  6, "___"));               // produces "Alien_"echo (str_pad($input,  3, "*"));                 // produces "Alien" /*function substr(s, begin, end) {var ns = "", end = end || s.length;for (var i = begin; i < end; i++) {ns += s.charAt(i);}return ns;}*/

  

* Run:

 

javascript 實現php str_pad

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.