javascript 实现php str_pad

* 查看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

// test
function 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:

 

posted @ 2018-08-02 19:23  zhanghui_ming  阅读(267)  评论(0编辑  收藏  举报