Reputation: 167
I need to display the last part of a URL using javascript!
I am using this code but this will display the entire URL:
<script language="javascript">
document.writeln(document.location);
var url = $(this).attr("href");
var part = url.substring(url.lastIndexOf('/') + 1);
</script>
if the URL look like this:
domain.com/something/file
i need to only display the "file".
Upvotes: 7
Views: 13790
Reputation: 18462
The reason document.write(window.location)
writes the location is because of the toString
method of window.location
, which really returns window.location.href
.
// This will fallback to the location.pathname if this
// is not the location already or not an anchor.
var path = this.pathname || window.location.pathname;
var part = path.split('/').pop();
Pathname is everything after the domain name. So, http://example.com/something/file
breaks down like this:
http:
example.com
something/file
http://example.com/something/file
(there is also port, search (?this=that
) and hash (#hash
), which would both be empty in this case)
So, I'm taking something/file
and split
ting it into an array wherever this is a /
, which would be ["something", "file"]
After that I'm pop
ping off the last part of the array, in this case "file"
Both window.location
and any <a>
tag have these properties. So, if you need to parse a URL, you can do the following in javascript:
var anchor = document.createElement('a');
anchor.href = '/about'; // this could be any relative or absolute url
And now anchor
will have the all those properties if you need them. No need for a regex or anything.
UPDATE
In newer browsers (excluding IE unless you use url-polyfill), you can use URL
instead of an <a />
like so:
const url = new URL('/about', this.location)
// or if you don't care about the host, you can do the following
// const url = new URL('http://localhost/about')
This contains all the other information, plus url.searchParams
, which makes it so you don't have to parse the search string yourself either.
Upvotes: 14
Reputation: 358
replace(/-/g," ") and split(".html") will remove "hyphens" and ".html" from url,thus only keeping the path name only
var parts=window.location.pathname.split("/");
var query=parts[parts.length-1].split(".html");
query[0]=query[0].replace(/-/g," ");
document.write(query[0])
Upvotes: 0
Reputation: 15091
<script type="text/javascript">
var segment_str = window.location.pathname; // return segment1/segment2/segment3/segment4
var segment_array = segment_str.split( '/' );
var last_segment = segment_array.pop();
document.write(last_segment); // alerts segment4
</script>
JsFiddle: http://jsfiddle.net/HNMV3/1/
Upvotes: 8
Reputation: 12341
var pathname = window.location.pathname,
part = pathname.substr(pathname.lastIndexOf('/') + 1);
Upvotes: 1