Home > Article > Web Front-end > JavaScript front zero padding operation example_javascript skills
The example in this article describes the method of prefixing zeros in JavaScript. Share it with everyone for your reference. The details are as follows:
In many cases, in order to display the format, it is necessary to perform a leading 0 operation when a certain string is not full.
1. Traditional code
/** * 前补0操作 * @param number String 待操作字符串 * @param length int 目标长度 */ function addZero(number, length) { var buffer = ""; if (number == "") { for (var i = 0; i < length; i ++) { buffer += "0"; } } else { if (length < number.length) { return ""; } else if (length == number.length) { return number; } else { for (var i = 0; i < (length - number.length); i ++) { buffer += "0"; } buffer += number; } } return buffer; }
2. This code is more concise
function addZero(str,length){ return new Array(length - str.length + 1).join("0") + str; }
I hope this article will be helpful to everyone’s JavaScript programming design.