0

I'm trying to reformat the first date from a string with Javascript. The date begins in a UK format (dd/mm/yyyy), and needs to end up in ISO format (yyyy-mm-dd).

Here's my function:

function goSearch() {
    var dr = $('input[name=daterange]').val(); //  string is as follows: "05/03/2018 - 10/03/2018"
    var st = dr.substr(0,10);
    var ststring = st.replace(/\//g, '-'); // string is now: "05-03-2018"
    var stdd = ststring.substr(0,2); // produces "05"
    var stmm = ststring.substr(3,5); // produces "03-20"
    var styyyy = ststring.substr(6,10); // produces "2018"
    var stIso = styyyy + "-" + stmm + "-" + stdd; // final date is "2018-04-20-08"
}

I can't work out why the variable "stmm" (which is equal to ststring.substr(3,5) ) returns "03-20" as opposed to "03".

Thanks in advance.

jonhendrix
  • 366
  • 2
  • 15
  • 5
    The second parameter to `.substr()` is the *length* of the desired substring, not the terminating index. – Pointy Mar 05 '18 at 21:35
  • 3
    [`substring()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring) takes an index as 2nd parameter. – 001 Mar 05 '18 at 21:37
  • @Pointy Rookie question. Thanks for that. – jonhendrix Mar 05 '18 at 21:37
  • Doesn't answer original question, but you can go about it like this: `let exec = /(\d\d)\/(\d\d)\/(\d\d\d\d)/g.exec(str.match(/.*?(?= )/)[0])` and then `let newstring = \`${exec[3]}-${exec[2]}-${exec[1]}\`` (where `str` is your string) – vityavv Mar 05 '18 at 21:41

0 Answers0