Home >Web Front-end >JS Tutorial >JavaScript front zero padding operation example_javascript skills

JavaScript front zero padding operation example_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:10:221087browse

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.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn