Javascript删除url最后一段(如果找到的是数字)
我有javascript函数来映射url和超链接以突出显示菜单项,但是我不能在更深层的页面中使用url最后一段带有数字,url看起来像:Javascript删除url最后一段(如果找到的是数字),javascript,url,segment,Javascript,Url,Segment,我有javascript函数来映射url和超链接以突出显示菜单项,但是我不能在更深层的页面中使用url最后一段带有数字,url看起来像:http://localhost/story/89 我想删除最后一个url段,如果它是一个数字,那么url将以http://localhost/story(也可以剥离/) 您可以将正则表达式参数传递到split()中 只需将.split(/(\/\d*)$/)[0]添加到url.split(“?”[0].split(“#”)[0]函数中的stripQuerySt
http://localhost/story/89
我想删除最后一个url段,如果它是一个数字,那么url将以http://localhost/story
(也可以剥离/
)
您可以将正则表达式参数传递到
split()
中
只需将.split(/(\/\d*)$/)[0]
添加到url.split(“?”[0].split(“#”)[0]
函数中的stripQueryStringAndHashFromPath
的末尾
这个新的正则表达式段基本上是搜索一个反斜杠(\/
),后面跟一个或多个位于字符串末尾($
)的数字(\d*
)
更多关于正则表达式的信息
函数stripQueryStringAndHashFromPath(url){
url=url.split('?')[0]。split('#')[0]。split(/(\/\d*)$/)[0];
返回url;
}
log(stripQueryStringAndHashFromPath('http://localhost/story/89'));代码>
函数stripQueryStringAndHashFromPath(url){
url=url.split('?')[0]。split('#')[0]。split(/(\/\d*)$/)[0];
返回url;
}
log(stripQueryStringAndHashFromPath('http://localhost/story/89'));代码>函数validateURL(url){let lastSegment=url.split(“/”);if(lastSegment[(lastSegment.length)-1].match(/^[0-9]$/))console.log(“True Last Segmant”);}validateURL(“” 您这样做的目的是什么?要验证最后一个段,您可以使用以下代码:函数validateURL(url){let lastSegment=url.split(“/”);if(lastSegment[(lastSegment.length)-1]。match(/^[0-9]$/)console.log(“True last Segmant”);else console.log(“False”)}validateURL(“)
/* highlight nav menu */
$(function(){
$('#topMain li a').each(function(index) {
if($.trim(this.href) == stripQueryStringAndHashFromPath(window.location.href)) {
$(this).closest('li').addClass('active')
.closest('li.parent').addClass('active');
}
});
});
function stripQueryStringAndHashFromPath(url) {
return url.split("?")[0].split("#")[0];
}
function validateURL(url){ let lastSegment = url.split("/");
if(lastSegment[(lastSegment.length)-1].match(/^[0-9]$/))
console.log("True Last Segmant");
}
validateURL("http://localhost/demo/8")