Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/373.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-按位置查找URL中的文本_Javascript_Jquery_Indexof - Fatal编程技术网

JavaScript-按位置查找URL中的文本

JavaScript-按位置查找URL中的文本,javascript,jquery,indexof,Javascript,Jquery,Indexof,这应该很容易,但我正在努力 我有一个启动函数的按钮。我还需要一个触发警报,告诉我用户在哪个页面上 www.whater.com/thispage1/whater www.whater.com/thispage2/whater www.whater.com/thispage3/whater 因此,在我的按钮被点击后,我想要一个回读“thispage1”或“thispage2”等的通知。我不想把整个URL反馈给我。有没有一种方法可以在url开始之前根据其位置或字符数在url中查找文本?查看并使用以提

这应该很容易,但我正在努力

我有一个启动函数的按钮。我还需要一个触发警报,告诉我用户在哪个页面上

www.whater.com/thispage1/whater

www.whater.com/thispage2/whater

www.whater.com/thispage3/whater

因此,在我的按钮被点击后,我想要一个回读“thispage1”或“thispage2”等的通知。我不想把整个URL反馈给我。有没有一种方法可以在url开始之前根据其位置或字符数在url中查找文本?

查看并使用以提取所需的位,然后查找要开始/结束的索引

var top_dir = window.location.pathname.slice(
    1,
    window.location.pathname.indexOf('/', 1)
);

也许这会帮助你开始。这里的关键角色是
window.location.pathname
string.split()


我想这就是您想要的。window.location.pathname.split(“/”)[1]?这也很有效,但您对字符串了解较少。把它作为另一个答案
var returnPage = function() {
    var urlString = window.location.pathname;
    var stringArray = urlString.split("/");

    return stringArray[0]; // number == whichever piece of the array you want to get
};

function myFunction() {
    alert(returnPage());
}