最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin3浏览0评论

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?

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?

Share Improve this question edited May 23, 2017 at 10:28 CommunityBot 11 silver badge asked Mar 21, 2012 at 20:48 ShawShaw 1731 gold badge1 silver badge8 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 8

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/Guffa/sEUHY/

http://jsfiddle/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 );
}

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'

Slightly improve @Guffa's anwser:

Now you can specify the total length after padding zero by given total_length parameter.

function addLeadingZero(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))

发布评论

评论列表(0)

  1. 暂无评论