admin 管理员组文章数量: 1086019
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 badges4 Answers
Reset to default 8You 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))
本文标签: javascript regex add leading zero to ALL number contained in stringStack Overflow
版权声明:本文标题:JavaScript, Regex, add leading zero to ALL number contained in string - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://roclinux.cn/p/1740168088a2145980.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论