Home  >  Article  >  Web Front-end  >  Detailed explanation of JavaScript string numbers left padding, right padding, fixed length, truncation extended function code

Detailed explanation of JavaScript string numbers left padding, right padding, fixed length, truncation extended function code

黄舟
黄舟Original
2017-03-27 14:23:133360browse

This article mainly introduces JavaScript StringNumber left padding, right padding, fixed length, truncation expansionFunction code, required Friends, you can refer to

Sometimes if our date is less than two digits, add a 0, etc., you can use this.

Everyone should understand this, so I won’t talk nonsense. The code is as follows:

String.prototype.padLeft =
Number.prototype.padLeft = function(total, pad) {
  return (Array(total).join(pad || 0) + this).slice(-total);
}

Test code:

//补位
"X".padLeft(5, "Y"); //返回:YYYYX
(50).padLeft(5);   //返回:00050

var x = 1;
x.padLeft(2);     //返回:01

//截位
(123).padLeft(2);   //返回:23

More codes

/**
 * 取子字符串
 * @param oriStr  原字符串
 * @param beginIndex 取子串的起始位置
 * @param len  取子串的长度
 * @return 子字符串
 */
 public String subString(String oriStr,int beginIndex,int len){
 int strlen = oriStr.length();
 beginIndex = beginIndex -1;
 if(strlen <= beginIndex){
  System.out.println("out of " + oriStr + "&#39;s length, please recheck!");
 }else if(strlen <= beginIndex+len){
  str = oriStr.substring(beginIndex);
 }else{
  str = oriStr.substring(beginIndex, beginIndex+len);
 }
 return str;
 }
 
 /**
 * 右补位,左对齐
 * @param oriStr 原字符串
 * @param len 目标字符串长度
 * @param alexin 补位字符
 * @return 目标字符串
 */
 public String padRight(String oriStr,int len,char alexin){
 int strlen = oriStr.length();
 if(strlen < len){
  for(int i=0;i<len-strlen;i++){
  str = str+alexin;
  }
 }
 str = str + oriStr;
 return str;
 }
 
 /**
 * 左补位,右对齐
 * @param oriStr 原字符串
 * @param len 目标字符串长度
 * @param alexin 补位字符
 * @return 目标字符串
 */
 public String padLeft(String oriStr,int len,char alexin){
 int strlen = oriStr.length();
 if(strlen < len){
  for(int i=0;i<len-strlen;i++){
  str = str+alexin;
  }
 }
 str = oriStr + str;
 return str;
 }

The above is the detailed content of Detailed explanation of JavaScript string numbers left padding, right padding, fixed length, truncation extended function code. For more information, please follow other related articles on the PHP Chinese website!

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