Dan*_*eis 43 javascript string
在javascript中填充字符串的最简单方法是什么?
我正在寻找一个内联表达式,相当于mystr.lpad("0", 4):for mystr='45'返回0045.
Dan*_*eis 144
找到一个简单的一线解决方案:
("0000" + n).slice(-4)
Run Code Online (Sandbox Code Playgroud)
如果字符串和填充在变量中,您将拥有:
mystr = '45'
pad = '0000'
(pad + mystr).slice(-pad.length)
Run Code Online (Sandbox Code Playgroud)
在这里找到答案,感谢@ dani-p.致@profitehlolz的积分.
Kev*_*sox 21
function pad(value, length) {
return (value.toString().length < length) ? pad("0"+value, length):value;
}
Run Code Online (Sandbox Code Playgroud)
如下所示:
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"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
63233 次 |
| 最近记录: |