[英]Regular Expression that matches any string of characters up to “/” Javascript
I have a Javascript function that loops through href navigation and matches it to the url location. 我有一个Javascript函数循环通过href导航并将其匹配到url位置。 If the two match then an "active" class is added.
如果两者匹配则添加“活动”类。 This works great, except for when someone goes to a page like "services/service1".
这很有效,除非有人去了“services / service1”这样的页面。 How would I add the logic to look a string like "services/service1" or "blog/post1" and trim to just "services/" and "blog/"?
我如何添加逻辑来查找像“services / service1”或“blog / post1”这样的字符串并修剪为“services /”和“blog /”?
Here is my current function 这是我目前的职能
scope.$on("$routeChangeSuccess", function (event, current, previous) {
var location = current.$$route.originalPath;
var selectionhref = element.children().find('a');
//Searches for match of routepath url and href, removes siblings active, adds active
(function(){
element.children().each(function(index){
console.log(location);
if($(selectionhref[index]).attr('href') == location){
$(this).siblings().removeClass('active');
$(this).addClass('active');
};
});
})()
}); //routeChangeSuccess
没有RE或Split
简单方法;
var root = location.substr(0, (location + "/").indexOf("/") + 1);
Use the replace
function. 使用
replace
功能。 It accepts a variety of params, one being a regular expression and the replacement string. 它接受各种参数,一个是正则表达式和替换字符串。
> "services/service1".replace(/[^\/]+$/, "")
'services/'
[^\\/]+
matches any character but not a forward slash /
one or more times. [^\\/]+
匹配任何字符,但不匹配正斜杠/
一次或多次。 $
asserts that we are at the end of a line. $
断言我们在一条线的尽头。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.