Take the 2-minute tour ×

What is best way to convert absolute path to relative path by javascript or jquery ?

for example consider as below :



share|improve this question
add comment

2 Answers

up vote 6 down vote accepted

Use the trick that <a> elements contain location properties.

$("<a href='http://localhost:2011/Content/Images/Product/Large/3.jpg'>")
share|improve this answer
Excellent trick! Can you refer to any documentation explaining that 'pathname' prop? What are the other props we can rely on? –  abernier Jun 17 '12 at 9:50
@abernier: Here's a list. It does state it's HTML5, though. I'm not aware of cross-browser support. –  pimvdb Jun 17 '12 at 9:52
add comment

Just use window.location.pathname

share|improve this answer
And some string manipulation to convert it manualy ? –  AnyOne Aug 31 '11 at 15:52
@AnyOne basically –  Neal Aug 31 '11 at 15:52
There is no a method provided naturaly by javascript or jquery ? –  AnyOne Aug 31 '11 at 15:53
@AnyOne: It's 2-3 lines of code. No need for a library function: Take the length of the host part, make sure that the URL starts with the host part, create substring starting at host-part.length. –  Aaron Digulla Aug 31 '11 at 16:01
add comment

Your Answer


