Javascript line splitting

I am trying to extract the article id from the following href:

/MarketUpdate/Pricing/9352730

I just want to extract the id at the end of the line and use the following code:

    var $newsLink = $(this).attr('href');

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

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

+3
source share
2 answers
var $newsString = $newsLink.substr($newsLink.lastIndexOf('/')+1);

Please note that your assumption is that it is '/'present in the line and there is an identifier after it. A safer way to do this check is if it is possible that the '/'identifier may be missing or missing, it would first be checked using:

if ($newsLink.lastIndexOf('/') != -1 && $newsLink.lastIndexOf('/') + 1 < $newsLink.length) {
    var $newsString = $newsLink.substr($newsLink.lastIndexOf('/')+1);
}
+7
source

/, substr , :

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

Source: https://habr.com/ru/post/1755775/


All Articles