2013-08-15 2 views
1

URL의 특정 부분을 분할하고 싶습니다. 여기까지 있습니다.자바 스크립트 스플릿 URL

<script type='text/javascript'> 
var query = window.location.pathname.split('/'); 
query = window.location.pathname.split('.html'); 

var redirectpath = "http://www.mydomain.com/search/?q=" 
window.location.href = redirectpath + query; 
</script> 

의 URL 구조는 다음과 같이 될 것이다 : 이런 변수 query 출력

http://www.mydomain.com/page/2013/05/some-page-title.html 

; page,2013,05,some-page-title

오직 some-page-title 부분 만 필요하며 하이픈도 제거하십시오.

때문에 최종 출력이 될 것 http://www.mydomain.com/search/?q=some page title

어떻게 가능할까요? 도와주세요!! 감사합니다.

+0

분할을'pathname'' "/"'저장 후 URL의 일부를 원하는 가정. 배열의 마지막 항목 ('var page = query.pop();')을 제거하고 ".html":'page = page.replace (/ \. html $ /, "");'를 제거한 다음 "-": "page : page.replace (/ -/g," ");'와 함께 마지막 문자열을 만드십시오 :'var redirectpath ="http://www.mydomain.com/search/?q = "+ 페이지; ' – Ian

답변

6

스플릿은 배열을 반환하고 배열로 사용합니다!

var parts = window.location.pathname.split('/'); 
var query = parts[parts.length-1].split('.html'); 

query[0]= query[0].replace(/-/g," "); 

var redirectpath = "http://www.mydomain.com/search/?q=" 
window.location.href = redirectpath + query[0]; 

것은이 항상 query``에 의해 마지막 /

+0

거의 완료되었습니다. 이제 하이픈 만 제거해야합니다. –

+2

나는 당신의 대답을 편집하고 단지 하이픈 제거를 추가 할 자유를 가져 갔다. :) – Alejandra

+0

^너희들은 대단하다.) 나는이 게시물을 나중에 나에게 투표하기 위해 북마크했다. 투표 명성 *) –

0
//get the url 
           var url = window.location; 
           //function to get the hostname and pathname 
           //var l = getLocation(url); 
           //split the pathname by/
           var array = url.pathname.split('/'); 

           //fix the url protocol and hostname for concate 
           var pathnames = window.location.protocol + "//" + window.location.host; 

           //loop to get the splited url pathname and insert the each url in specific div 
           for (i = 1; i < array.length; i++) { 

            //concatenate the path for each loop 
            pathnames = pathnames + '/' + array[i]; 

            //appending an ancher tag with href for path in the element with id table_panel_header 
            $("div#table_panel_header").append(
              '<a href="' + pathnames + '">' 
                + array[i] + '</a>/'); 
           } 

           //example text seen as: Complaint_Module/master/complaint-items/ 

           /* example href will append like 
           <div id="table_panel_header"> 
           <a href="http://localhost:8010/Complaint_Module">Complaint_Module</a>/ 
           <a href="http://localhost:8010/Complaint_Module/master">master</a>/ 
           <a href="http://localhost:8010/Complaint_Module/master/complaint-items">complaint-items</a>/ 
           </div> */