是否可以使用正则表达式将带有前导零的相同数字替换为字符串中的数字

时间:2020-12-15 19:29:44

Say I have a string "abc123def45"

说我有一个字符串“abc123def45”

Is it possible, with javascript regex to replace all the numbers in the string to be either the same length or all at a fixed length of, say, 6 digits.

是否有可能,使用javascript正则表达式将字符串中的所有数字替换为相同的长度或全部固定长度,例如6位数。

So, if going for the 6 digits approach, the resulting string would be "abc000123def000045"

因此,如果采用6位数方法,结果字符串将为“abc000123def000045”

And if going for the same length approach (which I suspect will be harder if not impossible with regex), the resulting string would be "abc123def045"

如果采用相同长度的方法(我怀疑使用正则表达式会更难,如果不是不可能),结果字符串将是“abc123def045”

I can certainly find all the numbers with regex with something like:

我当然能用正则表达式找到所有数字,例如:

\d+

but how do I get the right amount of leading zeros in the replacement?

但是如何在替换中获得正确数量的前导零?

Sample code:

var s = "abc123def45";
var r = s.replace(/\d+/g, "000123"); // this is wrong of course

2 个解决方案

#1


3  

You can use:

您可以使用:

var s = "abc123def45";
var r = s.replace(/\d+/g, function($0) {
      return new Array(6-$0.length+1).join('0')+$0; });
//=> "abc000123def000045"

#2


2  

I can't think of a way that doesn't use a function as a callback in replace, e.g.:

我想不出一种不使用函数作为替换回调的方法,例如:

var zeros = "0000000000";
var r = s.replace(/\d+/g, function(m) {
    return zeros.substring(0, 6 - m.length) + m;
});

Complete example: Live Copy

完整示例:实时复制

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Zero Padding with RegEx</title>
</head>
<body>
  <script>
    (function() {
      "use strict";

      var s = "abc123def45";
      var zeros = "0000000000";
      var r = s.replace(/\d+/g, function(m) {
        return zeros.substring(0, 6 - m.length) + m;
      });
      display("Result: " + r);

      function display(msg) {
        var p = document.createElement('p');
        p.innerHTML = String(msg);
        document.body.appendChild(p);
      }
    })();
  </script>
</body>
</html>

#1


3  

You can use:

您可以使用:

var s = "abc123def45";
var r = s.replace(/\d+/g, function($0) {
      return new Array(6-$0.length+1).join('0')+$0; });
//=> "abc000123def000045"

#2


2  

I can't think of a way that doesn't use a function as a callback in replace, e.g.:

我想不出一种不使用函数作为替换回调的方法,例如:

var zeros = "0000000000";
var r = s.replace(/\d+/g, function(m) {
    return zeros.substring(0, 6 - m.length) + m;
});

Complete example: Live Copy

完整示例:实时复制

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Zero Padding with RegEx</title>
</head>
<body>
  <script>
    (function() {
      "use strict";

      var s = "abc123def45";
      var zeros = "0000000000";
      var r = s.replace(/\d+/g, function(m) {
        return zeros.substring(0, 6 - m.length) + m;
      });
      display("Result: " + r);

      function display(msg) {
        var p = document.createElement('p');
        p.innerHTML = String(msg);
        document.body.appendChild(p);
      }
    })();
  </script>
</body>
</html>