3

I am trying to extract an article ID from the following href:

/MarketUpdate/Pricing/9352730

I just want to extract the ID at the end of the string and am using the following code:

 var $newsLink = $(this).attr('href');
 var $newsString = $newsLink.substr($newsLink.lastIndexOf('/'));

However this returns the final '/' which i do not want.

asked Jul 21, 2010 at 14:39

2 Answers 2

7
var $newsString = $newsLink.substr($newsLink.lastIndexOf('/')+1);

Note that your assumption here is that the '/' is present in the string and there's an ID after it. A safer way to do this check if there's a chance '/' might not be present or the ID is missing would be to check for it first using:

if ($newsLink.lastIndexOf('/') != -1 && $newsLink.lastIndexOf('/') + 1 < $newsLink.length) {
 var $newsString = $newsLink.substr($newsLink.lastIndexOf('/')+1);
}
answered Jul 21, 2010 at 14:40
Sign up to request clarification or add additional context in comments.

Comments

2

You can skip the / character by telling the substr call to start one character after the index, like this:

var $newsString = $newsLink.substr($newsLink.lastIndexOf('/') + 1);
answered Jul 21, 2010 at 14:40

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.