JavaScript,正则表达式,将前导零添加到字符串中包含的所有数字 [英] JavaScript, Regex, add leading zero to ALL number contained in string

查看:60
本文介绍了JavaScript,正则表达式,将前导零添加到字符串中包含的所有数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个 Perl 脚本是我想在 JavaScript 中实现的():

This Perl script is what I want to implement in JavaScript (source):

s/([0-9]+)/sprintf('%04d',$1)/ge;

显然 sprintf 在 JavaScript 中不可用,但我知道您可以构建一个直接处理关注数量的函数,但是在我的情况下,我有一个长字符串,其中可能包含多个要转换的数字像这样的字符串:abc8 23 123 变成这样:abc000008 000023 000123(以6位为例).

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.

我真的想避免后一种方法,因为 1) 在这种情况下速度是一个问题,并且 2) 在正确的位置拆分字符串所涉及的正则表达式似乎比在这一点上添加前导零更难.

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.

最后,用 JavaScript 的正则表达式还有其他方法吗?

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

演示:http://jsfiddle.net/Guffa/sEUHY/

这篇关于JavaScript,正则表达式,将前导零添加到字符串中包含的所有数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆