Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript, Regex, add leading zero to ALL number contained in string

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?

like image 356
Shaw Avatar asked Dec 28 '22 03:12

Shaw


2 Answers

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/

like image 58
Guffa Avatar answered Dec 29 '22 17:12

Guffa


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 );
}
like image 23
Billy Moon Avatar answered Dec 29 '22 16:12

Billy Moon