How do I trim/strip the URL down to the page name? - javascript

How would I go about trimming/stripping the URL down to the page name...
So: http://www.BurtReynoldsMustache.com/whatever/whoever/apage.html
Would become: apage.html
Any ideas?

you do not need jquery:
var url = window.location.href;
var page = url.substring(url.lastIndexOf('/') + 1);
Edit: a good point of the possible query string:
// it might be from browser & / anywhere else
var url = window.location.href;
url = url.split('#').pop().split('?').pop();
var page = url.substring(url.lastIndexOf('/') + 1);
ok, if the location object is available, use pathname gives better result as show below, however, a url can be a string or something directly from text field or span/label. So above solution should have its place.

With location and any link (<a>) elements on the page, you get a load of properties that give you specific parts of the URL: protocol, host, port, pathname, search and hash.
You should always use these properties to extract parts of the URL in preference to hacking about with href and probably getting it wrong for corner cases. For example, every solution posted here so far will fail if a ?query or #fragment is present. The answers from Rob and digitalFresh attempt to cope with them, but will still fail if a / character is present in the query string or fragment (which is valid).
Instead, simply:
var pagename= location.pathname.split('/').pop();

Most of the solutions here are not taking advantage of the window.location object. The location object has this wonderful thing called pathname which returns just the path, no query string, host, protocol, hash, etc.
var mypage = window.location.pathname.split("/").pop();

You could do something like this:
document.location.href.split('/').pop();
Edit: you probably want to get rid of the query string if there is one also:
document.location.href.split('/').pop().split('?').shift();
Edit 2: this will also ignore an anchor in the url if there is one
document.location.href.split('/').pop().split(/\?|#/).shift();

This should also exclude query and hash values.
var path = location.href;
path = path.substring(path.lastIndexOf("/") + 1);
path = path.split("?")[0].split("#")[0];
console.debug(path);

Haven't tested so compeltely guessed, but I'm sure something like this will do :-)
var url = 'http://www.BurtReynoldsMustache.com/whatever/whoever/apage.html';
var page = url.split('/');
alert(page[page.length-1]);​
EDIT Tested under jsfiddle and it was wrong, the above code should now work :-)

Related

How to trim off the query part of a url using javascript alone?

I've scowerd stackoverflow & for some reason this question is simply not answered in a clear enough manner for me to get right..
I have a url pathname www.thisurl.com/this/url/is/generic%877948
I want to console log the url alone, trimming off the query part of so that all I get is: www.thisurl.com.
I've tried the following:
var pathtotrim = location.href.split('/').pop();
document.write(pathtotrim);
console.log("hello", pathtotrim);
But this trims off the beginning of the url leaving me with /this/url/is/generic%877948.
Essentially doing the opposite of what I want. How can I trim off the query part of a url to be console logged.. please!!!???
Try this:
var pathtotrim = location.href.split('/')[0];
This will split the string on the / but will take the first segment (in your case that would be www.x.com)
Edit:
Like Leilo Faieta Said, location.host or location.hostname would be quicker.
var pathtotrim = "www.thisurl.com/this/url/is/generic%877948".split('/')[0];
document.write(pathtotrim);
console.log("hello", pathtotrim);
let url = 'www.thisurl.com/this/url/is/generic%877948'
console.log(url.replace(/\/.*/g, ''));
There is no need to manipulate strings: you can just use location.host or location.hostname.
This will give you the www part of the url.
on this url:
https://www.google.com/search?safe=off&source=hp&ei=P9SXW7_RO9CKmgWiybjIBA&q=location&oq=location&gs_l=psy-ab.3..0j0i131k1j0l8.269799.273393.0.273746.20.13.4.1.1.0.156.1198.8j4.13.0....0...1c.1.64.psy-ab..2.18.1341.6..35i39k1j0i10k1.98.Zbh8pzpSLkY
you will get
www.google.com
If you want to have all the first part of the url including the http protocol
location.protocol + '//' + location.host
on the same example url you will get
https://www.google.com

Change the pathname in the URL of a link while keeping the querystring constant

From a page with the following URL, http://example.com/foo.html?query=1&other=2, I want to create a link to http://example.com/bar.html?query=1&other=2. How do I do that without explicitly saving and reloading all the query strings.
I need this to easily link from an iframe version of a page (embed.html?query) to the full page (index.html?query).
I would have recommended using the Location object's search method (available at document.location or window.location) to pull out the parameters, then modify the rest of the URL, but that API is apparently specific to Firefox.
I would simplify #DMortensen's answer by just splitting on the first ?, then modifying the first part (which will be the URL's path portion only), and reapplying the second part.
If you need to parse the parameters, I recommend the jQuery plugin Query Parameter Parser: one call to $.parseQuery(s) will pull out an object of all the keys & values.
It can be finicky, but you could split the URI on '?' and then loop through the 2nd element of that array to grab the key/val pairs if you need to evaluate each pair (using '&' as a delimiter). The obvious weakness in this would be if there are additional '?' or '&' used in the URI.
Something like this maybe? (pseudocode-ish)
var URI = document.URL;
var qs = URI.split('?');
var keyvalpair = qs[1].split('&');
var reconstructedURI = '&' + keyvalpair;
for(var i = 0; i< keyvalpair.length; i++){
var key = keyvalpair[i].split('=')[0];
var val = keyvalpair[i].split('=')[1];
}
Thank you for all the answers. I tried the following and it works.
function gotoFullSite() {
var search = window.location.search;
window.open("http://example.com/"+search)
}
$('#clickable').click(gotoFullSite);
and then use <a id = "clickable" href="#"></a>. When I click the link, it opens the proper website with all the query parameters in a new tab. (I need a new tab to break out of an iframe.)

Get specific part of url of a link

I want to get a specific part of a url between the third and fourth slashes of a link on the page.
EDIT: Sorry I don't think I was clear the first time, I meant getting the specific part of the url OF A LINK found on the page.
var getSegment = function (url, index) {
return url.replace(/^https?:\/\//, '').split('/')[index];
}
Usage:
getSegment("http://domain.com/a/b/c/d/e", 4); // "d"
The replace makes sure that the first two slashes after the protocol (http or https) don't count.
Here's a working example of getting a particular path segment.
Code:
var url = "www.test.com/one/two/three?p1=v&p2=v#anc";
var file = url.split('?')[0];
var pathanddomain = file.split('/');
var path = pathanddomain.splice(1, pathanddomain.length-1);
var pathIndexToGet = 2;
document.write(path[pathIndexToGet]);​
If you want to do this for the current page, use:
var url = window.location.href;
Also, if your url starts with http(s)://, you will need to remove this.
I'd suggest:
var link = 'http://www.example.com/directory1/directory2/directory3/directory4/index.html';
console.log(link.split('/')[5]);​
JS Fiddle demo.
The reason we're using [5] not [4] is because of the two slashes at the beginning of the URL, and because JavaScript arrays are zero-based.
you should elaborate you question and should specify which is your domain, that means on what purpose you are asking that question ??
This may help you:
var urlValue = url.split("/");
Then store urlValue as array.
then pick up third and forth value of the urlvalue on array.

Add body #id based on url

Need help! I've been looking for a solution for this seemingly simple task but can't find an exact one. Anyway, I'm trying to add custom #id to the tag based on the page's URL. The script I'm using works ok when the URLs are like these below.
- http://localhost.com/index.html
- http://localhost.com/page1.html
- http://localhost.com/page2.html
-> on this level, <body> gets ids like #index, #page1, #page2, etc...
My question is, how can I make the body #id still as #page1 or #page2 even when viewing subpages like this?
- http://localhost.com/page1/subpage1
- http://localhost.com/page2/subpage2
Here's the JS code I'm using (found online)
$(document).ready(function() {
var pathname = window.location.pathname;
var getLast = pathname.match(/.*\/(.*)$/)[1];
var truePath = getLast.replace(".html","");
if(truePath === "") {
$("body").attr("id","index");
}
else {
$("body").attr("id",truePath);
}
});
Thanks in advance!
edit: Thanks for all the replies! Basically I just want to put custom background images on every pages based on their body#id. >> js noob here.
http://localhost.com/page2/subpage2 - > my only problem is how to make the id as #page2 and not #subpage2 on this link.
Using the javascript split function might be of help here. For example (untested, but the general idea):
var url = window.location.href.replace(/http[s]?:\/\//, '').replace('.html', '');
var segments = url.split('/');
$('body').id = segments[0];
Also, you might want to consider using classes instead of ID's. This way you could assign every segment as a class...
var url = window.location.href.replace(/http[s]?:\/\//, '').replace('.html', '');
var segments = url.split('/');
for (var i = 0; i < segments.length; i++) {
$('body').addClass(segments[i]);
}
EDIT:
Glad it worked. Couple of notes if you're planning on using this for-real: If you ever have an extension besides .html that will get picked up in the class name. You can account for this by changing that replace to a regex...
var url = window.location.href.replace(/http[s]?:\/\//, '');
// Trim extension
url = url.replace(/\.(htm[l]?|asp[x]?|php|jsp)$/,'');
If there will ever be querystrings on the URL you'll want to filter those out too (this is the one regex I'm not 100% on)...
url = url.replace(/\?.+$/,'');
Also, it's a bit inefficient to have the $('body') in every for loop "around" as this causes jQuery to have to re-find the body tag. A more performant way to do this, especially if the sub folders end up 2 or 3 deep would be to find it once, then "cache" it to a variable like so..
var $body = $('body');
for ( ... ) {
$body.addClass( ...
}
Your regex is only going to select the last part of the url.
var getLast = pathname.match(/./(.)$/)[1];
You're matching anything (.*), followed by a slash, followed by anything (this time, capturing this value) and then pulling out the first match, which is the only match.
If you really want to do this (and I have my doubts, this seems like a bad idea) then you could just use window.location.pathname, since that already has the fullpath in there.
edit: You really shouldn't need to do this because the URL for the page is already a unique identifier. I can't really think of any situation where you'd need to have a unique id attribute for the body element on a page. Anytime where you're dealing with that content (either from client side javascript, or from a scraper) you should already have a unique identifier - the URL.
What are you actually trying to do?
Try the following. Basically, it sets the id to whatever folder or filename appears after the domain, but won't include a file extension.
$(document).ready(function() {
$("body").attr("id",window.location.pathname.split("/")[1].split(".")[0]);
}
You want to get the first part of the path instead of the last:
var getFirst = pathname.match(/^\/([^\/]*)/)[1];
If your pages all have a common name as in your example ("page"), you could modify your script including changing your match pattern to include that part:
var getLast = pathname.match(/\/(page\d+)\//)[1];
The above would match "page" followed by a number of digits (omitting the 'html' ending too).

javascript window location href without hash?

I have:
var uri = window.location.href;
That provides http://example.com/something#hash
What's the best and easiest way to get the entire path without the #hash?
uri = http://example.com/something#hash
nohash = http://example.com/something
I tried using location.origin+location.pathname which doesn't work in every browser. I tried using location.protocol+'//'+location.host+location.pathname which looks like kind of a crappy solution to me.
What is the best and easiest way to do so? maybe I query for location.hash and try to substr() this from the uri?
location.protocol+'//'+location.host+location.pathname is the correct syntax if you do not care about port number or querystring
If you do care:
https://developer.mozilla.org/en/DOM/window.location
location.protocol+'//'+
location.host+
location.pathname+
(location.search?location.search:"")
or
location.protocol+'//'+
location.hostname+
(location.port?":"+location.port:"")+
location.pathname+
(location.search?location.search:"")
You can also just do a location.href.replace(location.hash,"")
It will remove EVERYTHING from the FIRST # and on regardless of other hash characters in the string
Alternatively create a URL object:
const url = new URL("https://www.somepage.com/page.hmtl#anchor") //(location.href);
console.log(url)
url.hash="";
console.log(url)
var uri = window.location.href.split("#")[0];
// Returns http://example.com/something
var hash = window.location.hash;
// Returns #hash
location.href.replace(location.hash,"")
Is the universal way also the smaller?
location.href.split(/\?|#/)[0]
Shorter solutions:
without query string and hash location.href.split(location.search||location.hash||/[?#]/)[0]
only without hash location.href.split(location.hash||"#")[0]
(I usually use the first one)
ES2020:
let [uri, hash] = location.href.split("#");
console.log(uri, hash);
location.hash = "#myhash";
[uri, hash] = location.href.split("#");
console.log(uri, hash);
I was looking for this answer:
`${window.location.origin}${window.location.pathname}${window.location.search}`
location.href = window.location.href.split("write here your code to delete in your URL")[0] + "write here your final destination";

Categories