ghilton
ghilton

Reputation: 127

(Javascript) How to extract the last part of the current URL - without the file extension?

I currently have the following javascript code working:

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

Lets say the current URL is http://www.example.com/products/0033.htm

The javascript produces a hyperlink to http://www.example.com/contact.php?id=0033.htm

How do I modify this script so that urlPath1 and the eventual hyperlink is without the ".htm" part?

Upvotes: 2

Views: 2240

Answers (2)

Grace Huang
Grace Huang

Reputation: 5679

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>'); 

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324620

Do exactly what you did to get the filename, but split on . instead of / and take the first piece.

Upvotes: 1

Related Questions