与javascript正则表达式的精确字符串匹配
我很可能是一个非常简单的正则表达式问题。我正在研究一个简单的原型,并且需要知道我在哪个页面上,所以如果用户单击菜单窗口小部件导航到相同视图,则不会重新加载它。与javascript正则表达式的精确字符串匹配
我有两个网址,用户可以切换之间:
http://localhost/TestMVC/Larry/LarryTiles
http://localhost/TestMVC/Larry/LarryTilesList
的网址,也可以有一些尾随查询字符串的项目,如: http://localhost/TestMVC/Larry/LarryTilesList?filterValue=servers
LarryTiles是给我是这个问题。 “/ \ bLarryTiles \ b /”星期五(在其他问题的回答之后)在这里工作,但现在不匹配。 :)
我需要找到这两个URL中的字符串“LarryTiles”和“LarryTilesList”,但无法完全弄清楚如何做到这一点。我的本地机器和它托管的各种服务器之间的URL发生了变化,所以我不能依靠位置。
编辑:添加了一个尾随查询字符串的例子,我忘记了。对不起:(
?您可以使用此代码:
str = 'http://localhost/TestMVC/Larry/LarryTiles?filterValue=servers';
if (str.match(/\/([^\/?]+)(?=\/$|\?|$)/)) {
if (match[1] == 'LarryTiles')
alert('LarryTiles found');
else if (match[1] == 'LarryTilesList')
alert('LarryTilesList found');
}
你可以得到这样一个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
}
好像你解释什么作品,或尝试这样的:http://jsfiddle.net/Wfz9d/
你有一个区分大小写问题
案件不是问题,虽然这些都是使用的网址。 – dex3703 2012-04-05 22:04:46
这很容易出现尾随斜线。 – jfriend00 2012-04-05 21:53:07
同意但OP的问题中的网址没有斜线。 – anubhava 2012-04-05 21:56:32
基于你最近编辑的问题,我更新了我的答案来处理'尾部斜线','查询字符串'等情况。 – anubhava 2012-04-05 22:19:59