Skip to content Skip to sidebar Skip to footer

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

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;
});

Demo: http://jsfiddle.net/Guffa/sEUHY/

Solution 2:

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){ 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"