This Perl script is what I want to implement in JavaScript (source):
s/([0-9]+)/sprintf('%04d',$1)/ge;
Obviously sprintf is not available in JavaScript, but I know you can build a function that work directly on the number of concern, however in my case I have a long string containing possibly multiple numbers to convert string such as this: abc8 23 123
into this: abc000008 000023 000123
(using 6 digits as an example).
So it's either some clever regex that I don't get, or somehow find some way to split the long string into an array of distinct string and numbers and only act on the number one by one.
I really want to avoid the latter approach because 1) Speed is an issue in this case, and 2) The regex involved in splitting strings at the right place seems harder than adding leading zeros at this point.
In the end, is there any other way to go about it with JavaScript's regex?
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;
});
Demo: http://jsfiddle.net/Guffa/sEUHY/
http://jsfiddle.net/hHfUC/1/
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){ return zeroFill(parseInt(x),6) })
Requred zeroFill
function
function zeroFill( number, width ){
if ( number.toString().length >= width )
return number;
return ( new Array( width ).join( '0' ) + number.toString() ).substr( -width );
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With