Remove leading zeroes in datestring

I have a date string like the following: 2011-02-03. I want to remove the leading zeroes in the day and month part of the string. How do I do this?

Answers:

Answer
"2011-02-03".replace(/-0+/g, '-'); // => "2011-2-3"

[Update]

Per @Lucky's question, you can account for other formats that might have a leading zero as such:

"02-03".replace(/(^|-)0+/g, "$1"); // => "2-3"
Answer

The naive way to do this is to split the string on -, then if the value at index 1 or 2 starts with a 0, replaceAll 0 with ''. Something like (I didn't test this)

var tokens = '2011-02-03'.split('-'),
    mm = tokens[1],
    dd = tokens[2];

if (mm.charAt(0) === '0') tokens[1] = mm.replace("0", "");
if (dd.charAt(0) === '0') tokens[2] = dd.replace("0", "");

var newString = tokens[0] + "-" tokens[1] + "-" + tokens[2];
Answer

You can use the library http://www.datejs.com/ which give you a lot of formatting option if you do not want to use the substring method.

Answer

Without regex:

function stripLeadingZerosDate(dateStr){
    return dateStr.split('-').reduce(function(date, datePart){
        return date += parseInt(datePart) + '-'
    }, '').slice(0, -1);
}

stripLeadingZerosDate('01-02-2016')      // 1-2-2016
stripLeadingZerosDate('2016-02-01')      // 2016-2-1

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.