索引上的indexOf和lastIndexOf的问题 - 从字符串中获取URL的一部分

str*_*ght 7 javascript regex jquery substring indexof

我有几个问题以我想要的方式分解字符串.我有这样的网址:

http://SomeAddress.whatever:portWhatever/someDirectory/TARGETME/page.html
Run Code Online (Sandbox Code Playgroud)

我正在尝试使用substring和indexOf而不是regex来获取字符串上的TARGETME部分.这是我现在正在使用的功能:

 function lastPartofURL() {
    // Finding Url of Last Page, to hide Error Login Information
    var url = window.location;
    var filename = url.substring(url.lastIndexOf('/')+1);
    alert(filename);
}
Run Code Online (Sandbox Code Playgroud)

然而,当我写这篇文章时,我的目标是"page.html"部分,这就是它返回的内容,但是我无法重新配置它以完成我现在要做的事情.

如果可能的话,我希望它来自字符串的开头而不是结尾,因为在我尝试定位之前应该总是有一个url然后是一个目录,但我对这两种解决方案都很感兴趣.

这是一个类似的正则表达式,但它不安全(根据JSLint),因此我不介意用更实用的东西替换它.

 /^.*\/.*\/TARGETME\/page.html.*/
Run Code Online (Sandbox Code Playgroud)

Sha*_*ard 7

正如其他人已经回答的那样,.split()对你的情况有好处,但假设你的意思是返回URL的"前一部分"(例如也返回"TARGETME" http://SomeAddress.whatever:portWhatever/dirA/DirB/TARGETME/page.html),那么你不能使用固定数字而是先取项目最后一个数组:

function BeforeLastPartofURL() {
    var url = window.location.href;
    var parts = url.split("/");
    var beforeLast = parts[parts.length - 2]; //keep in mind that since array starts with 0, last part is [length - 1]
    alert(beforeLast);
    return beforeLast;
}
Run Code Online (Sandbox Code Playgroud)