Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prepend a zero in front of any number below 10 in Javascript using Regexp

Good day,

Is there a Regex that I could use to prepend a 0 before any number that is below 10?

I am not looking for a date parsing library, ternary or if/else solutions. (hopefully)

var currentDate = new Date(),
    stringDate = currentDate.getFullYear() + "-" + currentDate.getMonth() + "-" + currentDate.getDate() + " " + currentDate.getHours() + ":" + currentDate.getMinutes() + ":" + currentDate.getSeconds();

    alert( stringDate ); //2011-10-17 10:3:7

I would like a RegExp that I could apply to stringDate to get 2011-10-17 10:03:07

Thank you very much!

like image 261
Cybrix Avatar asked Nov 17 '11 15:11

Cybrix


People also ask

How do you put a zero in front of a string?

The format() method of String class in Java 5 is the first choice. You just need to add "%03d" to add 3 leading zeros in an Integer. Formatting instruction to String starts with "%" and 0 is the character which is used in padding. By default left padding is used, 3 is the size and d is used to print integers.

How to use RegEx function in JavaScript?

As mentioned above, you can either use RegExp() or regular expression literal to create a RegEx in JavaScript. const regex1 = /^ab/; const regex2 = new Regexp('/^ab/'); In JavaScript, you can use regular expressions with RegExp() methods: test() and exec() .

What is RegExp object in JavaScript?

Regular expressions are patterns used to match character combinations in strings. In JavaScript, regular expressions are also objects. These patterns are used with the exec() and test() methods of RegExp , and with the match() , matchAll() , replace() , replaceAll() , search() , and split() methods of String .


4 Answers

Just add the leading 0 every time, then use slice(-2) to get the last two characters, like so:

('0' + currentDate.getHours()).slice(-2)
like image 102
Alex Peattie Avatar answered Oct 08 '22 20:10

Alex Peattie


The following function will allow you to declare a minimum length for a number along or within a string and will pad it with zeros to make it the appropriate length.

var PrependZeros = function (str, len, seperator) {
    if(typeof str === 'number' || Number(str)){
        str = str.toString();
        return (len - str.length > 0) ? new Array(len + 1 - str.length).join('0') + str: str;
    }
    else{
        for(var i = 0,spl = str.split(seperator || ' '); i < spl.length; spl[i] = (Number(spl[i])&& spl[i].length < len)?PrependZeros(spl[i],len):spl[i],str = (i == spl.length -1)?spl.join(seperator || ' '):str,i++);
        return str;
    }
};

For those wanting a less cryptic version

var PrependZeros = function (str, len, seperator) {
    if (typeof str === 'number' || Number(str)) {
        str = str.toString();
        return (len - str.length > 0) ? new Array(len + 1 - str.length).join('0') + str : str;
    }
    else {
        var spl = str.split(seperator || ' ')
        for (var i = 0 ; i < spl.length; i++) {
            if (Number(spl[i]) && spl[i].length < len) {
                spl[i] = PrependZeros(spl[i], len)
            }
        }
        return spl.join(seperator || ' ');
    }
};

Examples:

PrependZeros("1:2:3",2,":"); // "01:02:03"
PrependZeros(1,2); // "01"
PrependZeros(123,2); // "123"
PrependZeros("1 2 3",3); // "001 002 003" 
PrependZeros("5-10-2012",2,"-"); //"05-10-2012"
like image 35
Davan Etelamaki Avatar answered Oct 08 '22 20:10

Davan Etelamaki


You don't need regex for that. You can make a simple pad function yourself:

function pad(n) {
    if (n < 10)
        return "0" + n;
    return n;
}

alert(pad(8));
alert(pad(11));

http://jsfiddle.net/DwnNG/

like image 24
Alex Turpin Avatar answered Oct 08 '22 20:10

Alex Turpin


I now this is old, but I just saw this simple and clean solution used on the w3c and just had to share it somewhere.

var hours = currentDate.getHours();
(hours < 10 ? '0' : '') + hours;
like image 39
John Avatar answered Oct 08 '22 20:10

John