3

I'm having a problem with substr() in JavaScript.
Please look at the code below.

The following works as expected. y = 2017

var add_date = "20170505";
var y = add_date.substr(0, 4);
alert(y);

But... the following doesn't work. It should return '05' but instead it returns 0505. m = 0505

var add_date = "20170505";
var m = add_date.substr(4, 6);
alert(m);

Could someone explain me what's wrong?

Thanks,

Nathan

Nathan
  • 491
  • 4
  • 8
  • @exebook What if I didn't know substring existed? – Nathan May 05 '17 at 21:10
  • Even without knowing `substring` existed, it would have taken a minimal amount of research for you to learn that `substr` didn't work the way you thought it did. – Shaggy May 05 '17 at 21:43

5 Answers5

5

.substr(4,6) method returns 6 characters starting at index 4. Use .substring instead.

var add_date = "20170505",
    y = add_date.substring(0, 4);
    console.log(y);


var add_date = "20170505",
    m = add_date.substring(4, 6);
    console.log(m);
kind user
  • 40,029
  • 7
  • 67
  • 77
3

The syntax for JavaScript's substr command is: string.substr(start, length). So the line of code should read:

var m = add_date.substr(4, 2);
Andy
  • 31
  • 2
2

The second parameter of String.substr specifies the number of characters to extract.

Your code should look as follows:

var add_date = "20170505";
var m = add_date.substr(4, 2);
alert(m);
le_m
  • 19,302
  • 9
  • 64
  • 74
2

The substr() has two arguments that specify a starting index and a length to extract.

You may be confusing it with the .substring() method that takes two arguments of start index and end index.

Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
1

The parameters of the SUBSTR function are start and length, not start and end

In the console you can see this:

"ABCDEFGHIJKL".substr(0,4)
"ABCD"

"ABCDEFGHIJKL".substr(4,6)
"EFGHIJ"

"ABCDEFGHIJKL".substr(4,2)
"EF"

So what you want is

.substr(4,2)
ProfDFrancis
  • 8,816
  • 1
  • 17
  • 26