I have a bunch of strings in javascript which hold dates such as "2015-02-17", how can I get the n last characters of that string as a substring like "02-17" or "17" ?
Asked
Active
Viewed 158 times
1
-
well, that's a quite basic thing. Did you try something? there is a very large amount of possible solutions for such a case, you can either use regular expressions or simply consider the string an array... Or substring.. Well.. – briosheje Apr 26 '15 at 12:24
-
I've tried slice and grabbing by index numbers, i'm looking for a clean solution – svarog Apr 26 '15 at 12:25
1 Answers
3
You could use the substring
method:
var x = '2015-02-17';
var last2Characters = x.substring(x.length - 2);
or slice
with a negative number:
var last2Characters = x.slice(-2);

Darin Dimitrov
- 1,023,142
- 271
- 3,287
- 2,928
-
-
Yeah slice would definitely work nice as well. Thanks for spotting on this. – Darin Dimitrov Apr 26 '15 at 12:27
-
coming from a java background, things like str.slice(-2) don't come naturally – svarog Apr 26 '15 at 12:45