简体   繁体   English

在Javascript中拆分字符串

[英]spliting a string in Javascript

I am trying to extract an article ID from the following href: 我试图从以下href中提取文章ID:

/MarketUpdate/Pricing/9352730

I just want to extract the ID at the end of the string and am using the following code: 我只想在字符串的末尾提取ID并使用以下代码:

    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. 请注意,您的假设是字符串中存在'/' ,并且后面有一个ID。 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: 更安全的方法是检查是否存在'/'可能不存在或ID丢失的情况是首先使用以下方法检查:

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

您可以通过告诉substr调用在索引后面开始一个字符来跳过/字符,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM