簡體   English   中英

正則表達式匹配任何字符串,最多為“/”Javascript

[英]Regular Expression that matches any string of characters up to “/” Javascript

我有一個Javascript函數循環通過href導航並將其匹配到url位置。 如果兩者匹配則添加“活動”類。 這很有效,除非有人去了“services / service1”這樣的頁面。 我如何添加邏輯來查找像“services / service1”或“blog / post1”這樣的字符串並修剪為“services /”和“blog /”?

這是我目前的職能

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/'

[^\\/]+匹配任何字符,但不匹配正斜杠/一次或多次。 $斷言我們在一條線的盡頭。

DEMO

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM