2
var string = "name t13 - cat y4 - dat s6";

should be changed to "name t13 - cat y04 - dat s06"

I need the string to always have at least two digit numbers. How can I change numbers within a string to lead with a zero if there is a single digit?

Daniel
  • 199
  • 1
  • 9
  • 1
    Have you tried anything yet? – j08691 Jan 14 '15 at 20:36
  • 1
    This question appears to be off-topic because it is about us doing your work for you. – Ryan Jan 14 '15 at 20:37
  • Use objects to hold these values. Hyphens are not made for separation of concerns. – Travis J Jan 14 '15 at 20:38
  • Are `cat` and `dat` fixed? – dfsq Jan 14 '15 at 20:38
  • If your only use case is adding a leading zero to single-digit numbers, that can easily be done with a quick&dirt regex search/replace. – MaiaVictor Jan 14 '15 at 20:41
  • possible duplicate of [regex: find one-digit number](http://stackoverflow.com/questions/15099150/regex-find-one-digit-number) – werfu Jan 14 '15 at 20:43
  • @TravisJ the string is part of loop that always changes. So it could be: `var string = "name t13 - cat y4 - dat s6";` or `var string = "others13y4sixs6";` Either way the single digits need a leading zero. – Daniel Jan 14 '15 at 20:53

1 Answers1

4

String.prototype.replace() accepts a regular expression as the first argument for pattern matching. You can also supply a function as the second argument which is called for each match and returns a replacement value.

var tests = [
    "s61 t1 e32 w2 i5 e600",
    "name t13 - cat y4 - dat s6",
    "others13y4sixs6"
];

tests.forEach(function(test){
    console.log(test.replace(/\D\d(?!\d+)/g, function(c) { 
        return c.charAt(0) + "0" + c.charAt(1); 
    }));
});
Jed Fox
  • 2,979
  • 5
  • 28
  • 38
canon
  • 40,609
  • 10
  • 73
  • 97
  • I needed this to work for characters at the start of the string as well so I had to change the function to this: `console.log(test.replace(/(^|\D)\d(?!\d+)/g, function(c) { if(c.length == 1) {return "0" + c.charAt(0);}else {return c.charAt(0) + "0" + c.charAt(1); }}));` – Zack Apr 05 '21 at 12:45