How can I get page URL from window.location.href
without decode in javascript?
For example we can not get exactly this URL: ;url=project_chart%2F%3Fproject_id%3D77
.
When we use window.location.href
in javascript , we will get this URL:
;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?!
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./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./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?!
- Browser decodes it for you. You can always url encode your string in JS. But why you need exactly the same URL? – Justinas Commented Mar 14, 2018 at 15:50
- real url? you mean example.? or example./report or what? – Joe Warner Commented Mar 14, 2018 at 15:50
- Pretty sure he means the url with all the % signs and values – Eugenio Commented Mar 14, 2018 at 15:51
-
@JoeWarner, i want
http://example./report#title=example_report&url=project_chart%2F%3Fproject_id%3D77
– saleh mosleh Commented Mar 14, 2018 at 15:51 -
Have you tried
document.url
? – Eugenio Commented Mar 14, 2018 at 15:52
4 Answers
Reset to default 4Try 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 ments.
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 pletely 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;