Javascript 左填充字符串的最简单内联方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13859538/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 14:58:06  来源:igfitidea点击:

Simplest inline method to left pad a string

javascriptstring

提问by Daniel Reis

Possible Duplicate:
Is there a JavaScript function that can pad a string to get to a determined length?

可能的重复:
是否有一个 JavaScript 函数可以填充字符串以获得确定的长度?

What's the simplest way to left pad a string in javascript?

在javascript中左填充字符串的最简单方法是什么?

I'm looking for an inline expression equivalent to mystr.lpad("0", 4): for mystr='45'would return 0045.

我正在寻找一个相当于mystr.lpad("0", 4): for will mystr='45'return的内联表达式0045

回答by Daniel Reis

Found a simple one line solution:

找到了一个简单的单行解决方案:

("0000" + n).slice(-4)

If the string and padding are in variables, you would have:

如果字符串和填充在变量中,您将有:

mystr = '45'
pad = '0000'
(pad + mystr).slice(-pad.length)

Answer found here, thanks to @dani-p. Credits to @profitehlolz.

答案在这里找到,感谢@dani-p。归功于@profitehlolz。

回答by Kevin Bowersox

function pad(value, length) {
    return (value.toString().length < length) ? pad("0"+value, length):value;
}

回答by xdazz

Something like below:

像下面这样:

String.prototype.lpad = function(padString, length) {
    var str = this;
    while (str.length < length)
        str = padString + str;
    return str;
}
console.log('45'.lpad('0', 4)); // "0045"