javascript / jquery get URL without hash - javascript

I know I can read the hash value of a URL with javascript/jquery. But is is possible that I can read the trailing bit? Finding the last piece of the URL
I have a domain. http://www.blah.com/
each section of the domain resides under a URL that is slug like "this-page" example
http://www.blah.com/service/
(with or without the trailing slash) But I want to know if I can find "service" in the URL with JavaScript, without Server Side intervention. I know I could do it if I had
http://www.blah.com/#service
I don't know Im just curious, I really don't know what I would look for otherwise so this is my first stop in my search cause I am clueless..

var p = location.pathname;
p = p.substring(p.length-1) == '/' ? p.substring(0, p.length-1) : p;
p.split('/').pop();

Use regex:
last_bit = $(location).attr('href').replace(/https?:\/\/[^\/]+/i, "");

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;

decodeURI / replace %20 in URL issues

The following code is used to get URL parameters.
<script type="text/javascript">
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
</script>
<script type="text/javascript">
var url = window.location.protocol + "//" + window.location.hostname;
</script>
The page with the above code is accessed from a link on another page. Within that link i'm passing in a news item ID and Title.
When the page with the above code loads the Title in the URL has %20 in place of all spaces.
I've read up on this and found i need to use decodeURI or decodeURIComponent. I've tried to do this in a number of places and alerted the result in the browser but i can't seem to get rid of the %20 from the title within the URL so its obvious i'm not doing it in the right place.
this is my result....
http://PAGE URL HERE/NewsArchive.aspx?Story=New%20site%20launched&ID=17
I believe i somehow need to include a regular expression of /%20/g,"-" in the replace of the parts variable, however i have next to no knowledge of regex.
Could someone let me know what i need to do as i'm drawing a blank. I've seen a number of similar articles but nothing that explains it to my low level of knowledge.
I also post on SharePoint Stack Exchange as this is being used with SharePoint but i haven't had any answers that have worked for me.
Any help appreciated.
I am not sure I understand the question, but it seems like you just want to retrieve the parameters? If you open the developer console (f12 in chrome) on the page with parameters in the URL you can type window.location and see all the properties of the object. If you type window.location.href you can see the full URI. An easy way to separate this is using .split.
window.location.href.split('?')[1] will give you everything after the ? character. You can do decodeUri(window.location.href.split('?')[1]) to get a normal string.
Just keep in mind the arrays returned by split are zero indexed.
Edit in response to the comment:
The technology you're looking for is history.replaceState. More details here. I would highly recommend a thorough skimming.
history.replaceState(null, "/NewsArchive.aspx", "Story=New-site-launched&ID=17")

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]];
}

Replace end characters of current URL with bookmarklet

Is there a way to replace all characters after the last backslash in the currentURL with another string via javascript bookmarklet?
I'm doing a lot of auditing work with Sharepoint sites and having to manually look at the settings pages for sites by entering strings to the end of a URL. For example, I might go to a site like:
https://site.com/..../default.aspx
And I replace the "default.aspx" with "_layouts/user.aspx" and reload the new page so it is now at:
https://site.com/..../_layouts/user.aspx
It's not always "default.aspx", so I can't just use a simple string replace. I know there is a way to manipulate the URL via a javascript bookmarklet, but my knowledge of how to do that is limited at best. Any help or guidance would be greatly appreciated
I don't know if this is what you thought, but if you just want to change the last part of the url with something else, you could use this bookmarklet
javascript:(function(){
var curloc = document.location.href.split('/');
var urlEnding= '/_layouts/user.aspx';
curloc = curloc.splice(0,curloc.length-1).join('/')+urlEnding;
document.location.href = curloc;
})();
You could replace the fixed url with
prompt('Enter your url:', '_layouts/user.aspx');
if you need to change the last part each time.
I hope this helps.

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.

Categories