Javascript - how to remove domain from location.href - javascript

I need to remove the domain name from location.href using Javascript. I have links like: http://localhost/App/User/UserOrder.aspx?id=949abc91-a644-4a02-aebf-96da3ac7d8e1&type=MO and I need to have links without http://localhost and in future without it's real domain name.
I will use those trimed links in Javascript function so I would like to trim it also in Javascript.
I have tried: window.location.href.split('/')[2]; but I could only get domain form it. And I want to get rid of domain.
Any help here much appreciated!

Use window.location.pathname. This gives you the path relative to the host. See here for more details.
For any arbitrary URL, assuming that the variable url contains your URL, you can do:
url = url.replace(/^.*\/\/[^\/]+/, '')

Rather than doing string manipulation on window.location.href, you can use the other properties of window.location. In your case, you want the pathname, the search and the hash:
console.log(window.location.pathname + window.location.search + window.location.hash);

I posted this on your other question as a comment but I might as well add it here too. You can use a replace with a regex, like this:
location.href.replace(/.*\/\/[^\/]*/, '')

Things have changed a bit since 2011 when the original answer was posted. Now you can use the URL Web API.
https://developer.mozilla.org/en-US/docs/Web/API/URL
For your question, the following code:
let dummy_url = new URL("http://localhost/App/User/UserOrder.aspx?id=949abc91-a644-4a02-aebf-96da3ac7d8e1&type=MO");
console.log( "pathname : " + dummy_url.pathname );
console.log( "search : " + dummy_url.search );
console.log( "both : " + dummy_url.pathname + dummy_url.search );
Generates the following output.
pathname : /App/User/UserOrder.aspx
search : ?id=949abc91-a644-4a02-aebf-96da3ac7d8e1&type=MO
both : /App/User/UserOrder.aspx?id=949abc91-a644-4a02-aebf-96da3ac7d8e1&type=MO
The combined pathname and search fields is what you want.
As of Nov 2021 this is available in everything except IE and Opera Mini.

Try this:
window.location.pathname
Fiddle: http://jsfiddle.net/maniator/zKruK/

Related

how to get page url without decode in javascript?

How can I get page URL from window.location.href without decode in javascript?
For example we can not get exactly this URL: http://example.com/report#title=example_report&url=project_chart%2F%3Fproject_id%3D77.
When we use window.location.href in javascript , we will get this URL:
http://example.com/report#title=example_report&url=project_chart/?project_id=77.
But I want to get exactly the same real URL.
Any solution?
Edited
as #Eugenio told, $(document)[0].URL works fine , but Is it safe?!
Try to use encodeURI.
As for example;
var url = window.location.href;
var originalUrl = encodeURI(url);
This function(encodeURI) encodes special characters,
except: , / ? : # & = + $ #
You can use encodeURIComponent() to encode these characters.
You can use encodeURIComponent, but you have to get the part of a string you want to encode.
encodeURIComponent(window.location.href.split('&url=')[1])
Or you can use RegExp to be more precise.
Just to make a clear and concise answer I will sum up all the comments.
For your problem the best solution is to use document[x].url where x is the index of the URL part that you want to use.
The main difference for your problem between window.location.href and document.url is that the last one gives you the URL in a string format, whilest the other return the URL already parsed.
Using either one is completely normal and safe and is widely adopted in all modern browsers.
var url1 = document.URL;
var url2 = window.location.href;
document.getElementById("documentUrl").append (url1);
document.getElementById("windowLocationUrl").append (url2);
<div id="documentUrl">document.url: </div>
<div id="windowLocationUrl">window.location.href: </div>
There is no difference in this particular snippet example because there are no parameters attached to the URL. Anyway, hope this helped. Cheers!
as #Eugenio told,
i use below code and it works fine:
var url = $(document)[0].URL;

JS split OR Logical Operator

User inputs a web address that I want to get only the tail from, as I do know what site he inputs.
So first I want to remove the "main" URL and get what ever is at the end, so my action is:
Original link: http://example.com/something
var n=e.split("http://example.com/");e=n[1];
And I will get "something"
The problem is that site can also be secured, thus having https not http. Therefore the split wont work.
How do I define a split function, that would work like this:
split("http://example.com/ || https://example.com/")
I do not want to split by looking at "//" or anything of that sort, I want an exact address.
If you like it clear and want to avoid regular expressions, try this:
var n=e.split("http://example.com/",2).pop().split("https://example.com/",2).pop();
If you wish to know the host you can do so by using this code instead in JavaScript:
window.location.host
Source Get The Current Domain Name With Javascript (Not the path, etc.)
You can also use window.location.path to get the URL that was requested, combining those you get:
window.location.host + window.location.pathname
For me, this outputs stackoverflow.com/posts/25203020/edit while writing this reply.
var s = "http://example.com/something";
function split (url) {
var r = /([^:]+):\/\/([^\/]+)\/(.*)/gi;
var a = r.exec(url)
return [a[1], a[2], a[3]];
}

How to get the parts of a url using document.referrer?

I need to use document.referrer to get the previous URL I also need to be able to get the parts of the URL like:
window.location.protocol
window.location.host
window.location.pathname
but I can't figure out how to do it with document.referrer. Anyone got any ideas?
You can create an a element with the referrer as its url.
a elements (with hrefs) can act like location objects
var a=document.createElement('a');
a.href=document.referrer;
alert([a.protocol,a.host,a.pathname].join('\n'));
a='';
There's no equivalent to window.location with regards to document.referrer so your only option will be to break down the string itself. You could write a regex to do that or rely on a series of string splits:
var parts = document.referrer.split('://')[1].split('/');
var protocol = document.referrer.split('://')[0];
var host = parts[0];
var pathName = parts.slice(1).join('/');
If you want the convenience and can afford the weight, have a look at URI.js or one of the suggested URL parsers. If you don't need anything fancy, <a>s href decomposition will do the job just fine.

What's an easy way to get the url in the current window minus the domain name?

My Javascript ain't so hot, so before I get into some messy string operations, I thought I'd ask:
If the current url is: "http://stackoverflow.com/questions/ask"
What's a good way to to just get: "/questions/ask" ?
Basically I want a string that matches the Url without the domain or the "http://"
alert(window.location.pathname);
Here's some documentation for you for window.location.
ADDITIONAL ANSWER:
window.location.pathname itself is just not enough because it doesn't include the query part, and also URN if exists:
Sample URI = "http://some.domain/path-value?query=string#testURN"
window.location.pathname result = "/path-value"
window.location.search result = "?query=string"
pathname + search result = "/path-value?query=string"
If you want to get all the values just except the domain name, you can use the following code:
window.location.href.replace(window.location.origin, "")
Or as #Maickel suggested, with a simpler syntax:
window.location.href.substring(window.location.origin.length);
This gets the following URL parts correctly:
http://some.domain/path-value?query=string#testURN
alert(window.location.href.replace(window.location.origin, ""))--> "/path-value?query=string#testURN"
Use window.location.pathname.

How to Extract the Current URL and ID in jQuery?

How would I go about getting the current URL using jquery, or more specifically, getting an ID on the end of it?
For example, I have product.php#tab-2. What I want to get from it is just the '#tab-2' part.
I have tried 'window.location.pathname' but that will only return '/product.php'
Thanks
You don't need jQuery for this:
alert(window.location.href); // will give you the full url
alert(window.location.hash); // will give you the hash (#) value
See the Mozilla docs at window.location - MDC.
You want window.location.hash
Use jqUrl plugin (http://www.oakcitygraphics.com/jquery/jqURL/jqURLdemo.html) to retrieve the full current url, then strip the window.location.pathname part.
Thomas
To actually assign to a variable, use the following;
var url = window.location.href;
var id = url.substring(url.lastIndexOf('#') + 1);
Note that if your url is in this format /product.php/3 , then you can use the above code, just change the character is the lastIndexOf function.

Categories