Home > Web Front-end > JS Tutorial > body text

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

黄舟
Release: 2017-03-27 14:23:13
Original
3419 people have browsed it

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);
}
Copy after login

Test code:

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

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

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

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;
 }
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template