2012-02-04 1 views
8

이 문제를 조사하고 있었지만이 특정 목적을 위해 확실한 답을 찾을 수 없었습니다. 나는이 URL을 잡고 index.php를 제거 할 수 있습니다 ... 어떻게의 난의 URL을 가지고 있다고javascript/jquery를 사용하여 URL에서 파일 및 변수 가져 오기를 제거하려면 어떻게해야합니까?

http://mysite.com/stuff/index.php?search=my+search

하자? = 그것에서 나의 + 검색 그냥 http://mysite.com/stuff/ 될 것이라고 있도록 검색? 기본적으로 파일 이름없이 상위 URL을 가져 오거나 변수를 가져 오려면 ... URL에 상관없이 (사용하려는 모든 페이지의 기능을 사용자 정의 할 필요가 없음)

그래서 추가 예를 들어, 그냥 있다면 ...

http://mysite.com/silly.php?hello=ahoy

난 그냥 이

사람이를 알아내는 나에게 손을 줄 수 http://mysite.com

의 루트를 반환 할 것인가? 나는 완전히 잃어 버렸다.

답변

17

lastIndexOf("/")를 사용해보십시오 : 귀하의 URL이 str

var url = "http://mysite.com/stuff/index.php?search=my+search"; 
url = url.substring(0, url.lastIndexOf("/") + 1); 
alert(url); // it will be "http://mysite.com/stuff/" 

또는

var url = "http://mysite.com/silly.php?hello=ahoy"; 
url = url.substring(0, url.lastIndexOf("/") + 1); 
alert(url); // it will be "http://mysite.com/" 
+0

감사 index.php', 내가 지금 계속 lastIndexOf에서도 사용할 것입니다 상상 '이 포함됩니다. – Ian

+0

도와 드리겠습니다. – Aliostad

+0

'console.log (url)'은 경고보다 훨씬 낫습니다. – Tim

0

location.host 또는 location.hostname을 찾고 있습니다. 하지만 현재 URL이 아닌 완전한 문자열에서 추출하고 싶습니까?

내가 번 질문을 읽고 당신이 구성 문자열을 얻을 싶은 것 :

location.protocol + "//" + location.host + location.pathname 

권리를?

+4

'location.pathname'는 –

2

경우 :

newstr = str.replace(/\/[^\/]+$/,""); 

newstr 이제 경로를 포함뿐만 마지막 /에서 제외 문자열. 최종 /, 사용을 유지하기 :에

newstr = str.replace(/\/[^\/]+$/,"/"); 
2

분할을 "/", 슬래쉬 추가, 마지막 조각을 버리고 다시 그들과 합류.

var path = location.href.split('/'); 
path.pop(); 
path = path.join("/") + "/"; 
관련 문제