我正在努力解决一个可能非常简单的正则表达式问题。我正在开发一个简单的原型(prototype),需要知道我所在的页面,因此如果用户单击菜单小部件导航到同一 View ,我不会重新加载它。
我有两个用户可以在之间切换的 URL:
http://localhost/TestMVC/Larry/LarryTiles
http://localhost/TestMVC/Larry/LarryTilesList
URL 还可以有一些尾随查询字符串项,如下所示: http://localhost/TestMVC/Larry/LarryTilesList?filterValue=servers
LarryTiles 给了我这个问题。 “/\bLarryTiles\b/”在周五工作(在其他问题的回答之后),但现在不匹配。 :)
我需要在这两个 URL 中准确找到字符串“LarryTiles”和“LarryTilesList”,但不太清楚如何做到这一点。 URL 在我的本地计算机和托管它的各个服务器之间发生变化,因此我不能依赖位置。
编辑:添加了带有尾随查询字符串的示例,我忘记了。抱歉:(
最佳答案
您可以像这样获取 URL 的最后一个路径段:
function getLastPathSegment(url) {
var match = url.match(/\/([^\/]+)\/?$/);
if (match) {
return(match[1]);
}
return("");
}
// returns "LarryTiles"
getLastPathSegment("http://localhost/TestMVC/Larry/LarryTiles");
// returns "LarryTilesList"
getLastPathSegment("http://localhost/TestMVC/Larry/LarryTilesList");
所以,你可以这样做:
var endPath = getLastPathSegment(window.location.pathname);
if (endPath == "LarryTiles") {
// some code
} else if (endPath == "LarryTilesList") {
// some code
} else {
// some code
}
关于javascript - 与 javascript 正则表达式完全匹配的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10036427/