开发者

spliting a string in Javascript

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.


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);
}


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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜