3

Say I have a string "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.

So, if going for the 6 digits approach, the resulting string would be "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"

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
Graham
  • 6,569
  • 17
  • 57
  • 104
  • 1
    Do you want to use a regex for a particular reason? Or you want a solution and so far regex is the only way you think it's possible? – AD7six May 08 '14 at 09:46
  • I already have a solution, but wanted to use regex to be more succinct and supposedly more efficient – Graham May 08 '14 at 10:51

2 Answers2

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"
anubhava
  • 664,788
  • 59
  • 469
  • 547
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>
T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639