Chris
Chris

Reputation: 27384

Javascript substring acting strangely

I have created a function to turn a 24 hour string aka "0800" or "2330" into minutes. Sometimes the strings will drop leading zeros so I need to account for this.

It works BUT to get the minute component I try get the last two characters of the string which, one would assume, would be this:

var timeString = "800"; //Can be "0800"
timeString.substring(timeString.length - 2, 2)

Which, if your string is "800" (leading zero dropped) then it would be the equivalent to

timeString.substring(3 - 2, 2)

However this returns nothing what so ever. I only get "00" (what I'm looking for) if I use the following code:

timeString.substring(timeString.length, 2)

To me this code is wrong but it works, somehow?

Can anyone explain why? Have I misunderstood how this function is meant to work?

Upvotes: 0

Views: 442

Answers (4)

evilpie
evilpie

Reputation: 2941

So what you are doing is, getting the text from index 2 to 2, that's obviously is an empty string. You really want to use String.prototype.slice here. It allows you to use negative parameters as a way to index from the end (basically string-length - index). Specifying no second parameter will extract everything till the end of the string.

timeString.slice(-2)

Upvotes: 1

Michael Berkowski
Michael Berkowski

Reputation: 270607

You've confused the substring() function with the substr() function. substring()'s second parameter is the ending index of your substring, while substr()'s second parameter is the length of your string.

Try substituting substr() for substring()...

Upvotes: 0

Locksfree
Locksfree

Reputation: 2702

Here the second parameter is the index of the to character. What you are looking for is the substr function instead.

Upvotes: 1

Hunter McMillen
Hunter McMillen

Reputation: 61512

The second parameter in the substring method isn't the number of characters you want it is the index you want to go to. So right now you are going from substring(3-2, 2), index 2 to index 2, which gives you no characters.

Change it to:

timeString.substring(timeString.length-2, timeString.length)

Upvotes: 4

Related Questions