Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/446.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 子字符串上的indexOf和lastIndexOf问题-从字符串获取URL的一部分_Javascript_Jquery_Regex_Substring_Indexof - Fatal编程技术网

Javascript 子字符串上的indexOf和lastIndexOf问题-从字符串获取URL的一部分

Javascript 子字符串上的indexOf和lastIndexOf问题-从字符串获取URL的一部分,javascript,jquery,regex,substring,indexof,Javascript,Jquery,Regex,Substring,Indexof,我遇到了一些问题,以我想要的方式断开了一根线。我有这样一个url: http://SomeAddress.whatever:portWhatever/someDirectory/TARGETME/page.html 我尝试获取字符串上的TARGETME部分,使用substring和indexOf代替regex。这是我现在使用的函数: function lastPartofURL() { // Finding Url of Last Page, to hide Error Login

我遇到了一些问题,以我想要的方式断开了一根线。我有这样一个url:

http://SomeAddress.whatever:portWhatever/someDirectory/TARGETME/page.html
我尝试获取字符串上的TARGETME部分,使用substring和indexOf代替regex。这是我现在使用的函数:

 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);
}
然而,当我写这篇文章时,我的目标是“page.html”部分,这就是它返回的内容,但是我很难重新配置它来完成我现在想要它做的事情

如果可能的话,我希望它是从字符串的开头而不是结尾开始的,因为在我试图瞄准的目标之前,应该总是有一个url和一个目录,但我对这两种解决方案都感兴趣

这里有一个执行类似操作的正则表达式,但它不安全(根据JSLint),因此我不介意用更具功能的东西替换它

 /^.*\/.*\/TARGETME\/page.html.*/

使用
string.split()
可以更轻松地完成此任务

function getPath() {
    var url = window.location;
    var path = url.split("/")[4];
    alert(path);
    return path;
}
我只是建议使用这种方法,因为你说你总是知道URL的格式

 function lastPartofURL() {
    // Finding Url of Last Page, to hide Error Login Information
    var url = window.location;
    var arr = url.split('/');

    alert(arr[4]);
 }
请参见试试这个

    function lastPartofURL() {
    // Finding Url of Last Page, to hide Error Login Information
    var url = window.location;
    var sIndex = url.lastIndexOf('/');
    var dIndex = url.lastIndexOf('.', sIndex);
    if (dotIndex == -1)
    {
        filename = url.substring(sIndex + 1);
    }
    else
    {
        filename = url.substring(sIndex + 1, dIndex);
    }

    alert(filename);
}

正如其他人已经回答的那样,
.split()
适合您的情况,但是假设您打算返回URL的“最后一部分”(例如,
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;
}

这是一个伟大的解决方案!但是,正如您所承认的,它依赖于url始终保持不变,因此目前它仅限于我的范围。现在非常简短!这太棒了!这将使解决方案更加稳健。谢谢