javascript正则表达式url(url子字符串)

javascript regex url (url substring)

本文关键字:url 字符串 正则表达式 javascript      更新时间:2024-03-08

嘿,伙计们,我写了一个简单的函数,它读取当前的url并设置某种高亮显示。

如果我打开url,一切都很好,但如果我做了更高级的请求,它就不起作用了。

例如:如果我请求"/customers",它可以工作,但如果我请求了"/customers/10",它就不再工作了。有人能给我提供一些正则表达式操作吗?

提前感谢

function setGUI() {
var url = window.location.pathname;
switch(url) {
    case "/orders":
        $(document).ready(function() {
            $(".nav li:nth-child(2)").addClass("active");
        });
        break;
    case "/customers": // match "customers/any_id"
        $(document).ready(function() {
            $(".nav li:nth-child(3)").addClass("active");
        });
        break;
    case "/partners": match "partners/anyid"
        $(document).ready(function() {
            $(".nav li:nth-child(4)").addClass("active");
        });
        break;
    case "/help":
        $(document).ready(function() {
            $(".nav li:nth-child(5)").addClass("active");
        });
        break;
    case "/users/": // match "/users/any_id/"
        $(document).ready(function() {
            $(".nav li:nth-child(6)").addClass("active");
        });
        break;
    default:
        alert("debug");
    }
}
setGUI();

看起来您的函数不需要使用第二个斜杠之后的任何信息,所以我建议您只需删除第二个斜线之后的所有信息:

var url = window.location.pathname.replace(/^('/[^/]+)'/.*/, "$1");

然后让你的开关和箱子保持原样。

Switch将根据相等性进行评估。一种解决方案是使用if-else。我建议使用indexOf:

..
if(url.indexOf("/orders") > -1){
        $(document).ready(function() {
            $(".nav li:nth-child(2)").addClass("active");
        });
}else if(url.indexOf("/customers") > -1){
..