2012-06-06 2 views
2

나는 현재 다음과 같은 자바 스크립트 코드 작업이 있습니다(자바 스크립트) 파일 확장명없이 현재 URL의 마지막 부분을 추출하는 방법은 무엇입니까?

<script type="text/javascript"> 
    urlPath=window.location.pathname; 
    urlPathArray = urlPath.split('/'); 
    urlPath1=urlPathArray[2]; 
    document.write('<a href="http://www.example.com/contact.php?id='+urlPath1+'">test</a>'); 
    </script> 

현재 URL은 자바 스크립트 내가이 스크립트를 수정하려면 어떻게 http://www.example.com/contact.php?id=0033.htm

에 대한 하이퍼 링크를 생성 http://www.example.com/products/0033.htm

말할 수 있습니다를되도록 urlPath1 및 최종 하이퍼 링크에 ".htm"부분이 없습니까?

+0

파일 확장자는 크기가'.htm'입니까? –

+0

'urlPathArray [2];'마지막 요소를 얻기 위해'urlPathArray [urlPathArray.length - 1]'을 사용하십시오 ... –

답변

1

정확하게 파일 이름을 얻으려고했지만 / 대신 .으로 나눠서 첫 번째 곡을 가져옵니다.

+0

첫 번째 부분은'/ products/0033' 대신 0033를 사용합니다.'location.pathname'은 상대 경로를 반환합니다. –

0
var urlPath = window.location.pathname, 
    urlPathArray = urlPath.split('.'), 
    urlPath1 = urlPathArray[0].split('/').pop(); 

document.write('<a href="http://www.example.com/contact.php?id='+urlPath1+'">test</a>'); 
+0

점은 경로 이름의 중간에있을 수 있습니다. 경로의 마지막 세그먼트를 분리 한 다음 거기에있을 수있는 확장을 제거해야합니다. – jfriend00

+0

안녕하세요. 빠른 응답에 감사드립니다. 나는 당신의 모범을 보았지만 그것이 효과가없는 것 같습니다. 어떤 아이디어? – ghilton

+0

업데이트 : 다음 수정 된 코드를 사용하여 문제를 해결했습니다 : urlPath = window.location.pathname; urlPathArray = urlPath.split ('/'); urlPath1 = urlPathArray [urlPathArray.length - 1]; urlPath2 = urlPath1.split ('.'); productID = urlPath2 [0]; document.write ('test'); ' 도움을 다시 한번 감사드립니다. – ghilton

관련 문제