I need to get the last 2 characters from the href of a link and place them into a string.
I'm sure this is fairly simple but I seem to be struggling.
Here's the link
<a href="../mypage/?code=bb">test</a>
I need to grab the "bb" part of the href.
I need to get the last 2 characters from the href of a link and place them into a string.
I'm sure this is fairly simple but I seem to be struggling.
Here's the link
<a href="../mypage/?code=bb">test</a>
I need to grab the "bb" part of the href.
Share Improve this question asked Jan 12, 2011 at 11:49 TomTom 13k50 gold badges153 silver badges247 bronze badges 2- 3 Does this really make sense? Will the URL always be exactly in that form? – Pekka Commented Jan 12, 2011 at 11:52
- The URL will always end with a 2 letter code, yes – Tom Commented Jan 12, 2011 at 11:57
4 Answers
Reset to default 6Presuming link
is a reference to the element:
var chars = link.href.substr(-2);
If you need to get the reference to the link, it is best to give the link an ID attribute, e.g. <a href="../mypage/?code=bb" id="myLink">
, where myLink
is something that describes the link's purpose. You can then do this:
var chars = document.getElementById('myLink').href.substr(-2);
Finally, if what you want is the code
parameter from your link, it may be best to parse the URL into parts. If there is a chance that your URL may be more plex that what you've shown, you should do real URL parsing. As Rahul has pointed out in his answer there are some jQuery plugins that perform this function.
try
$(function() {
var res = $('a').attr('href').split(/=/)[1]
alert(res);
});
This will not grab the last two character, but everything after the =
sign which works probably more generic. And even if the <center> cannot hold
, regex could look like
$(function() {
var href = $('a').attr('href'),
res = /\\?code=(\w+)/.exec(href);
alert(res[1]);
});
var href = $('a').attr('href');
var last2char = href.substr(href.length-2);
You can try for some querystring plugins which might be a better option.