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