Reputation: 3830
What am I doing wrong?
I need to get the last 4 characters here
<div class="test">11/16/2001</div>
<script>
var lastfour = $(".test");
lastfour.substr(6);
</script>
Trying to get the year here. I know my syntax is awful, but I am just looking for the simplest solution.
Thanks!
Upvotes: 0
Views: 506
Reputation: 1199
Try this
<div class="test">11/16/2001</div>
<script>
var lastfour = $(".test").text();
lastfour.substr(-4);
</script>
Upvotes: 0
Reputation: 3133
The examples below use the following string. I've used numbers so it's easy to see what's going on.
var s = "1234567890";
Get all the characters in the string from the 8th (i.e. start = 7, because it's zero based):
s.substr(7); // returns 890
Get the first two characters from the string:
s.substr(0, 2); // returns 12
Get the last two characters from the string:
s.substr(-2); // returns 90
Get four characters starting from the 4th (i.e. start = 3):
s.substr(3, 4); // returns 4567
If start + length is greater than what's remaining in the string then only the characters to the end of the string included (obviously there isn't anything else to extract) so the resulting string may not be necessarily as long as what you are expecting. This is illustrated in the following example where length passed is 20 but the resulting string is only 4 characters long:
s.substr(6, 20); // returns 7890
Get two characters starting 4 from the end:
s.substr(-4, 2); // returns 78
String.substring(start, to)
String.substring() works slightly differently to String.substr() where the start and to positions are passed as arguments instead of start and length.
Upvotes: 1
Reputation: 1828
if last four, the best way is to use negative value, so it will be (with fixed variable as Sinetheta suggested):
<script>
var lastfour = $(".test").text().substr(-4);
</script>
also, you have extra )
in your script
lastfour.substr(6));
Edit (for future generations):
There is a bug in IE what James point out where negative value return whole string. This doesn't apply to IE9.
But slice()
function works in IE as well and it also accept negative values.
Upvotes: 1
Reputation: 2450
Does this only apply to a date in the mm/dd/yyyy format like in your example?
In that case this solution ( http://jsfiddle.net/TU4aF/ ) would be better.
var date = $(".test").text();
var splitDate = date.split('/');
var year = splitDate[2];
It can deal with single digit months and days.
Upvotes: 1
Reputation: 78780
$(".test");
returns a jquery object, not a string. You need to call .text()
to get the text.
Also, you have an extra )
.
This code also assumes that there is only one element which has a class of test
that you care about. If there are more, have a look at each
.
Upvotes: 4