2014-12-04 5 views
2

시나리오를 사용하여 URL 경로를 추출 내가 선두 슬래시를 제외하고 document.location에에서 경로 문자열을 추출 할정규 표현식

. 그래서 예를 들어, URL 인 경우 :

questions/ask 

것은이 간단합니다 :

http://stackoverflow.com/questions/ask 

내가 얻을 것

/* group everything after the leading slash */ 
var re = /\/(.+)/gi; 
var matches = document.location.pathname.match(re); 
console.log(matches[0]); 

을하지만 난 불을 지르고 콘솔에서이 코드를 실행하는 경우 , 나는 아직도 선도 슬래시를 얻는다. 나는 이미 regexp을 테스트했으며 regexp 엔진이 그룹을 올바르게 추출합니다.

질문

제대로 그룹 1 문자열을 어떻게 얻을?

답변

1

당신이 후행 말 또는 슬래시를 선도하고 있습니까? 귀하의 게시물에서 그것은 선도 슬래시처럼 보입니다.

그런데
document.location.pathname.replace(/^\//,"") 

, 당신의 정규 표현식은 바로,하지만 당신은 단지 matches[0] 전체 문자열이 정규 표현식과 일치하기 때문에 matches[1]가 일치하는 문자열에서 캡처 된 부분 동안, gi을 제거하고 matches[0]보다는 matches[1]을 읽을 필요 (정규 표현식에서 괄호로 인용).

var matches = document.location.pathname.match(/\/(.+)/); 
console.log(matches); // ["https://stackoverflow.com/questions/ask", "questions/ask"] 
+0

정확함, 슬래시를 의미합니다. 질문이 수정되었습니다. –

2

슬래시를 사용하지 않고 경로 이름을 얻고 싶다면 정규식이 필요하지 않습니다. location.pathname 항상 /로 시작하기 때문에 당신은 단순히 첫 번째 인덱스에서 문자열을 수행 할 수 있습니다

document.location.pathname.substr(1) // or .slice(1) 
+0

완벽한 KISS 답. –

1

정규식을 사용하여 당신이 할 수

var m = 'http://stackoverflow.com/questions/ask'.match(/\/{2}[^\/]+(\/.+)/); 
console.log(m[1]); /questions/ask