简体   繁体   English

正则表达式并切断url的第一部分(bootstrap活动类从navbar元素中删除)

[英]regex and cut off the first part of the url(bootstrap active class remove from navbar element)

I need some regex action. 我需要一些正则表达式操作。 It should cut off the ip part and look for the string after the "/". 它应该切断ip部分,并在“ /”之后寻找字符串。

www.IdontCareForThisPart/ButForThisIDoCare/ThanInsertWildcardHere www.IdontCareForThisPart / ButForThisIDoCare / ThanInsertWildcardHere

 $(function() {
     var url = document.URL.match(""); /* your awesome  regex here! */
     switch(url) {
         case "/Kalender":
             $('.cal').addClass("active");
             break;
         case "/Klienten":
             $('#asdf').addClass("active");
             break;
         case "/Aufgaben":
             $('.aufgaben').addClass("active");
             break;
         case "/Verwaltung":
             $('#verwaltung').addClass("active");
             break;
         case "/Willkommen":
             $('.nav > li:nth-child(1)').addClass("active");
             break;
         default:
             $('.nav > .active').removeClass();
             break;
     }
 });

Thank you for your time. 感谢您的时间。 Notes: I have changed the title of the question, now people who got the same problem can copy/paste this code. 注意:我已经更改了问题的标题,现在遇到相同问题的人可以复制/粘贴此代码。

www.IdontCareForThisPart/ButForThisIDoCare/ANDthisToo www.IdontCareForThisPart / ButForThisIDoCare / ANDthisToo

regex: 正则表达式:

[^/]*/(.*)

[^/] means NOT SLASH, * means 0 or more times The ( ) then capture what you want. [^ /]表示不放慢,*表示0次或多次()然后捕获您想要的内容。 On the inside of the ( ) is . 在()的内部是。 which means ANYTHING. 这意味着一切。

finally, if you are using / as your regex delimiter, you will have to escape the slashes: 最后,如果您使用/作为正则表达式分隔符,则必须转义斜线:

/[^\/]*\/(.*)/

So the exact code you need to add is 因此,您需要添加的确切代码是

url = url.replace(/[^\/]/,"")

This finds all the "not slashes" until it runs into a slash. 找到所有“非斜杠”,直到遇到斜杠为止。 All that found stuff is replaced with "" (nothing). 找到的所有内容都将替换为“”(什么都没有)。

You don't need regular expressions, just create an anchor linking the url, and get its pathName : 您不需要正则表达式,只需创建链接网址的锚,并获取其pathName

var a = document.createElement('a')
a.href = url;
a.pathName;

Or, in your case, if you want the path name of the current url, just use 或者,如果您要使用当前网址的路径名,则只需使用

location.pathname

The full code is 完整的代码是

var selector = {
    "/Kalender": '.cal',
    "/Klienten": '#asdf',
    "/Aufgaben": '.aufgaben',
    "/Verwaltung": '#verwaltung',
    "/Willkommen": '.nav > li:nth-child(1)'
}[location.pathname];
$(selector || '.nav > .active').toggleClass("active", !!selector);

For completeness here is the code which parses the first string after a the "/". 为了完整起见,这里是解析“ /”之后的第一个字符串的代码。

var url = window.location.pathname.split("/");
console.log(url[1]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM