使用 jQuery 在数字前面添加额外的零?

我有文件,这是上传的格式是这样的

一先生

二先生

100先生

二百先生

三百先生

等等。

我需要做的是增加额外的两个00之前,任何先生10和增加一个额外的0之前,MR10-99

所以文件是格式化的

001先生

010先生

076先生

等等。

任何帮助将是伟大的!

164753 次浏览
function addLeadingZeros (n, length)
{
var str = (n > 0 ? n : -n) + "";
var zeros = "";
for (var i = length - str.length; i > 0; i--)
zeros += "0";
zeros += str;
return n >= 0 ? zeros : "-" + zeros;
}


//addLeadingZeros (1, 3) =   "001"
//addLeadingZeros (12, 3) =  "012"
//addLeadingZeros (123, 3) = "123"

If you split on the space, you can add leading zeros using a simple function like:

function addZeros(n) {
return (n < 10)? '00' + n : (n < 100)? '0' + n : '' + n;
}

So you can test the length of the string and if it's less than 6, split on the space, add zeros to the number, then join it back together.

Or as a regular expression:

function addZeros(s) {
return s.replace(/ (\d$)/,' 00$1').replace(/ (\d\d)$/,' 0$1');
}

I'm sure someone can do it with one replace, not two.

Edit - examples

alert(addZeros('MR 3'));    // MR 003
alert(addZeros('MR 23'));   // MR 023
alert(addZeros('MR 123'));  // MR 123
alert(addZeros('foo bar 23'));  // foo bar 023

It will put one or two zeros infront of a number at the end of a string with a space in front of it. It doesn't care what bit before the space is.

Assuming you have those values stored in some strings, try this:

function pad (str, max) {
str = str.toString();
return str.length < max ? pad("0" + str, max) : str;
}


pad("3", 3);    // => "003"
pad("123", 3);  // => "123"
pad("1234", 3); // => "1234"


var test = "MR 2";
var parts = test.split(" ");
parts[1] = pad(parts[1], 3);
parts.join(" "); // => "MR 002"

This is the function that I generally use in my code to prepend zeros to a number or string.

The inputs are the string or number (str), and the desired length of the output (len).

var PrependZeros = function (str, len) {
if(typeof str === 'number' || Number(str)){
str = str.toString();
return (len - str.length > 0) ? new Array(len + 1 - str.length).join('0') + str: str;
}
else{
for(var i = 0,spl = str.split(' '); i < spl.length; spl[i] = (Number(spl[i])&& spl[i].length < len)?PrependZeros(spl[i],len):spl[i],str = (i == spl.length -1)?spl.join(' '):str,i++);
return str;
}

};

Examples:

PrependZeros('MR 3',3);    // MR 003
PrependZeros('MR 23',3);   // MR 023
PrependZeros('MR 123',3);  // MR 123
PrependZeros('foo bar 23',3);  // foo bar 023

I have a potential solution which I guess is relevent, I posted about it here:

https://www.facebook.com/antimatterstudios/posts/10150752380719364

basically, you want a minimum length of 2 or 3, you can adjust how many 0's you put in this piece of code

var d = new Date();
var h = ("0"+d.getHours()).slice(-2);
var m = ("0"+d.getMinutes()).slice(-2);
var s = ("0"+d.getSeconds()).slice(-2);

I knew I would always get a single integer as a minimum (cause hour 1, hour 2) etc, but if you can't be sure of getting anything but an empty string, you can just do "000"+d.getHours() to make sure you get the minimum.

then you want 3 numbers? just use -3 instead of -2 in my code, I'm just writing this because I wanted to construct a 24 hour clock in a super easy fashion.

In simple terms we can written as follows,

for(var i=1;i<=31;i++)
i=(i<10) ? '0'+i : i;

//Because most of the time we need this for day, month or amount matters.

Just for a laugh do it the long nasty way....:
(NOTE: ive not used this, and i would not advise using this.!)

function pad(str, new_length) {
('00000000000000000000000000000000000000000000000000' + str).
substr((50 + str.toString().length) - new_length, new_length)
}

I needed something like this myself the other day, Pud instead of always a 0, I wanted to be able to tell it what I wanted padded ing the front. Here's what I came up with for code:

function lpad(n, e, d) {
var o = ''; if(typeof(d) === 'undefined'){ d='0'; } if(typeof(e) === 'undefined'){ e=2; }
if(n.length < e){ for(var r=0; r < e - n.length; r++){ o += d; } o += n; } else { o=n; }
return o; }

Where n is what you want padded, e is the power you want it padded to (number of characters long it should be), and d is what you want it to be padded with. Seems to work well for what I needed it for, but it would fail if "d" was more than one character long is some cases.

Know this is an old post, but here's another short, effective way: zeros

edit: dur. if num isn't string, you'd add:

len -= String(num).length;

else, it's all good

function addLeadingZeros(sNum, len) {
len -= sNum.length;
while (len--) sNum = '0' + sNum;
return sNum;
}
var str = "43215";
console.log("Before : \n string :"+str+"\n Length :"+str.length);
var max = 9;
while(str.length < max ){
str = "0" + str;


}
console.log("After : \n string :"+str+"\n Length :"+str.length);

It worked for me ! To increase the zeroes, update the 'max' variable

Working Fiddle URL : Adding extra zeros in front of a number using jQuery?:

Note: see Update 2 if you are using latest ECMAScript...


Here a solution I liked for its simplicity from an answer to a similar question:

var n = 123


String('00000' + n).slice(-5); // returns 00123
('00000' + n).slice(-5);       // returns 00123

UPDATE

As @RWC suggested you can wrap this of course nicely in a generic function like this:

function leftPad(value, length) {
return ('0'.repeat(length) + value).slice(-length);
}


leftPad(123, 5); // returns 00123

And for those who don't like the slice:

function leftPad(value, length) {
value = String(value);
length = length - value.length;
return ('0'.repeat(length) + value)
}

But if performance matters I recommend reading through the linked answer before choosing one of the solutions suggested.

UPDATE 2

In ES6 the String class now comes with a inbuilt padStart method which adds leading characters to a string. Check MDN here for reference on String.prototype.padStart(). And there is also a padEnd method for ending characters.

So with ES6 it became as simple as:

var n = '123';
n.padStart(5, '0'); // returns 00123

Note: @Sahbi is right, make sure you have a string otherwise calling padStart will throw a type error. So in case the variable is or could be a number you should cast it to a string first:

String(n).padStart(5, '0');

str could be a number or a string.

formatting("hi",3);
function formatting(str,len)
{
return ("000000"+str).slice(-len);
}

Add more zeros if needs large digits

Try following, which will convert convert single and double digit numbers to 3 digit numbers by prefixing zeros.

var base_number = 2;
var zero_prefixed_string = ("000" + base_number).slice(-3);

By adding 100 to the number, then run a substring function from index 1 to the last position in right.

var dt = new Date();
var month = (100 + dt.getMonth()+1).toString().substr(1, 2);
var day = (100 + dt.getDate()).toString().substr(1, 2);


console.log(month,day);

you will got this result from the date of 2020-11-3

11,03

I hope the answer is useful