正则表达式匹配高达“/”的任何字符串Javascript
问题描述:
我有一个Javascript函数,通过href导航循环并将其匹配到url位置。如果两者匹配,则添加“活动”类。这很好,除了有人进入“services/service1”这样的页面时。我如何添加逻辑来查找像“services/service1”或“blog/post1”这样的字符串,并修剪为“services /”和“blog /”?正则表达式匹配高达“/”的任何字符串Javascript
这里是我当前的功能
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);
答
使用replace
功能。它接受各种参数,其中一个是正则表达式和替换字符串。
> "services/service1".replace(/[^\/]+$/, "")
'services/'
[^\/]+
匹配任何字符而不是正斜杠/
一次或多次。 $
声称我们在一条线的尽头。
'location.split( '/')移()+ '/'' – adeneo 2014-12-27 16:18:38
使用类似的技术,只是丢弃该'/'的最后部分的另一种选择:'location.split('/ ').reverse()。片(1).reverse()。加入('/')' – 2014-12-27 16:27:17