Javascript, Regex, Add Leading Zero To All Number Contained In String
Solution 1:
You can use a regular expression to find the numbers, and replace them with a value from a function:
s = s.replace(/\d+/g, function(m){
return"00000".substr(m.length - 1) + m;
});
Solution 2:
The regex is pretty simple, just pass the patched digits to a function, and return the modified match as replacement.
"abc8 23 123".replace(/\d+/g,function(x){ returnzeroFill(parseInt(x),6) })
Requred zeroFill
function
functionzeroFill(number, width ){
if ( number.toString().length >= width )
returnnumber;
return ( newArray( width ).join( '0' ) + number.toString() ).substr( -width );
}
Solution 3:
Or... yanno...
("0000"+var).slice(-4); // Normal old JS
`0000${var}`.slice(-4); // Sexier JS
The first evaluation coerces our variable var
into a string literal, prepending n 0's to it (so for a value of 123
we wind up with "0000123"
, then the slice starting from the end of the string (the negative modifier) counts backwards n character (so "0000123" or "0123").
The lovely part here is I can define a global constant (const ZedsPadBabyZedsPad='00000000000000';
) which is then usable for pretty much ANY typical lead-padding application, from 5-digit image number (img00011.jpg) to date (02/01/04) to (military) time: (07:00).
Don't want 0's? s'cool. STRING, baby.
`WhatACROCK${'you'}`.slice(-4) // 'ROCKyou'
Solution 4:
Slightly improve @Guffa's anwser:
Now you can specify the total length after padding zero by given total_length
parameter.
functionaddLeadingZero(str, total_length = 4) {
const leading_zeros = '0'.repeat(total_length)
str = str.replace(/\d+/g, function(m) {
return leading_zeros.substr(m.length) + m
})
return str
}
console.log(addLeadingZero("abc8 23 123", 0))
console.log(addLeadingZero("abc8 23 123", 5))
console.log(addLeadingZero("abc8 23 123", 6))
Post a Comment for "Javascript, Regex, Add Leading Zero To All Number Contained In String"