I'm using a script to add parameters to a URL to use with a if statement for a layout change. It works with a structure like this:
/Computers/Desktops
on click to change layout:
/Computers/Desktops?param=list
and
/Computers/Desktops?param=grid
I'm using a filer that adds parameter, then the layout will change between something like this:
/Computers/Desktops?param=list&fss=HP+2GB
and on click:
/Computers/Desktops?param=grid&fss=HP+2GB
This works well, but I need to make this work for another structure that looks like this:
/Computers/Desktops/Apple/Apple-iMac-Core-i5-2-7-GHz-8-GB-1-TB-LED-2?prodid=30811
Here I want to add the parameter before ?prodid=30811 so the layout changes on click between
/Desktops/Apple/Apple-iMac-Core-i5-2-7-GHz-8-GB-1-TB-LED-2?param=list&prodid=30811
/Desktops/Apple/Apple-iMac-Core-i5-2-7-GHz-8-GB-1-TB-LED-2?param=grid&prodid=30811
I hoped I just could change FSS in my script to prodid, but this doesn't work. So why doesn't it work and why, and how do I do this instead? My if/else script already works, I just need the correct URL from the buttonclick.
$('.click3').on('click', function() {
console.log("Clicked");
var baseUrl = window.location.href.split("?")[0];
var fss = getParametersByName("fss");
var params = getParametersByName("fss");
if (params == "list")
param = "grid";
else
param = "list";
var newUrl = baseUrl + "?param=" + param;
if ((fss).length > 0)
newUrl = newUrl + "&fss=" + fss;
window.location.href = newUrl;
function getParametersByName(name) {
name = name.replace(/[[]/, "\[").replace(/[]]/, "\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
});
I am using history.pushState to append few params to current page URL after making an AJAX call on my page. Now on same page based on user action, I want to update the page URL again with same or additional set of params. So my code looks like this:
var pageUrl = window.location.href + "?" + queryString;
window.history.pushState('','',pageUrl);
queryString is my list of query params.
For example, My Default page URL: http://sample.com/
After First AJAX call on same page URL should be: http://sample.com?param1=foo¶m2=bar
After Second AJAX call on same page URL can be:
http://sample.com/?param1=foo,foo1¶m2=bar¶m3=another_foo
But with the above code my params are getting appended to URL with the params and they look like below after second AJAX call:
http://sample.com?param1=foo¶m2=bar¶m1=foo,foo1¶m2=bar¶m3=another_foo
So the params appear twice in the URL, is there any way of replacing the params in URL before pushing to History or any other better way to achieve this in javascript(jquery) ?
I think what you need is remove window.location.href and leave '?' +.
var pageUrl = '?' + queryString;
window.history.pushState('', '', pageUrl);
This function might be helpful
function updateUrlParameter(param, value) {
const regExp = new RegExp(param + "(.+?)(&|$)", "g");
const newUrl = window.location.href.replace(regExp, param + "=" + value + "$2");
window.history.pushState("", "", newUrl);
}
Edit: The following solution is simpler, and it also works if the parameter is not yet part of the URL. However, it's not supported by Internet Explorer (you don't say?).
function setQueryStringParameter(name, value) {
const params = new URLSearchParams(window.location.search);
params.set(name, value);
window.history.replaceState({}, "", decodeURIComponent(`${window.location.pathname}?${params}`));
}
In order to keep the last part of the url and just play with parameters, you can create a new URL object like so:
// e.g url: sample.com/testpage/test
var url = new URL(window.location);
url.searchParams.set('foo', 'bar');
window.history.pushState({}, '', url);
// outcome: sample.com/testpage/test?foo=bar
// you can remove, just the param part, like so:
url.searchParams.delete('foo');
Manage query parameters in the current URL
This function is similar to the other answers, but without using RegExp and string concatenations.
Args:
name - string name of the query parameter.
value - string value of the parameter.
append - if true: this function always adds a new parameter. This is very useful when you need to add two parameters with the same name, e.g.: localhost:8080/some_page?foo=100500&foo=ABC. Otherwise, the parameter will be changed (or added if absent).
function setQueryStringParameter(name, value, append=false) {
const url = new URL(window.document.URL);
if (append) url.searchParams.append(name, value);
else url.searchParams.set(name, value);
window.history.replaceState(null, "", url.toString());
}
I'm splitting the current url into pieces but I'm doing something wrong with this part to get the current url. How can I solve this?
var url = window.location.url;
I'm trying to get the current url from the page. This is my function
function split(){
var url = window.location.url; // This part is not correct
var firstSplit = url.split('?')[1];
var name = firstSplit.split('&')[0];
var age = firstSplit.split('&')[1];
var parName = name.split('=')[0];
var nameName = name.split('=')[1];
var parAge = age.split('=')[0];
var ageAge = age.split('=')[1];
document.getElementById("nameId").innerHTML=naamName;
document.getElementById("ageId").innerHTML=leeftijdAge;
}
Use href:
window.location.href
For example running it on current SO page gives:
console.log(window.location.href);
this:
http://stackoverflow.com/questions/10783322/window-location-url-javascript
Add the following script to a page; it will display all the properties of the page's url:
document.write("<li>location.href = " + location.href);
document.write("<li>location.protocol = " + location.protocol);
document.write("<li>location.host = " + location.host);
document.write("<li>location.hostname= " + location.hostname);
document.write("<li>location.port = " + location.port);
document.write("<li>location.pathname = " + location.pathname);
document.write("<li>location.hash = " + location.hash);
document.write("<li>location.search = " + location.search);
better answer found here: https://gist.github.com/jlong/2428561
var parser = document.createElement('a');
parser.href = "http://example.com:3000/pathname/?search=test#hash";
parser.protocol; // => "http:"
parser.host; // => "example.com:3000"
parser.hostname; // => "example.com"
parser.port; // => "3000"
parser.pathname; // => "/pathname/"
parser.hash; // => "#hash"
parser.search; // => "?search=test"
You can access different parts of the URL directly by using different properties on window.location.
The full URL is window.location.href, but you seem to be more interested in the query string (the part after the question mark) which you can access with window.location.search
A list of other properties is can be found in the MDN article about window.location.
Try
var url = window.location.href;
Or
var url = document.URL;
and I think Please use function name something different then split because it is a function of PHP and may be reason of problem.
thanks
I'm not exactly sure what yo are trying to do after you break the URL into parts but here is how you can get the current URL and put them into variables. You can put them back together however you like latter. Source: [http://css-tricks.com/snippets/javascript/get-url-and-url-parts-in-javascript/][1]
var urlNow = window.location.pathname.split('/');
var itNow0 = urlNow[0];
var itNow1 = urlNow[1];
var itNow2 = urlNow[2];
var itNow3 = urlNow[3];
alert(itNow0+ ' ' +itNow1+ ' ' +itNow2+ ' ' +itNow3);
I've got a dropdown menu on my form, which when something is selected I need to reload the current page, but with an appended querystring.
How would I go about doing this?
This is an old question but it came up first in google search results.
The solution I went with is similar to jAndy's.
window.location.pathname gives me the page's url without the query string.
I'm then able to build the query string with "?"+$.param({'foo':'bar','base':'ball'}) which I then append to the pathname and set to window.location.href.
window.location.href = window.location.pathname+"?"+$.param({'foo':'bar','base':'ball'})
var params = [
"foo=bar",
"base=ball"
];
window.location.href =
"http://" +
window.location.host +
window.location.pathname +
'?' + params.join('&');
That code within your change event handler will do the trick.
For instance:
$('#my_dropdown_id').bind('change', function(){
var params = [
"foo=bar",
"base=" + $(this).val()
];
window.location.href = "http://" + window.location.host + window.location.pathname + '?' + params.join('&');
});
If you go with the top rated answer, you may want to replace
http://
in the code with
window.location.protocol
so that it works for other protocols, like https or file. So
window.location.href = window.location.protocol + "//" + window.location.host + window.location.pathname + '?' + params.join('&');
Actually, there a built-in function of location that you can use, the name of the function is assign.
For appending or modifying there is another built-in function of the URL class that you can use too. the name of the function is searchParams.
So for your case you just need below example:
const url = new URL(location.href);
url.searchParams.set('key', 'value');
location.assign(url.search);
Update 2022
I create a TypeScript function to apply redirect with params more easier:
const isClient = (): boolean => typeof window !== 'undefined';
type ParamsType = { [key: string]: string | number };
const redirectUrl = (url: string, params?: ParamsType): void => {
if (isClient()) {
try {
const _url = new URL(url);
if (params) {
const keyList = Object.keys(params);
for (let i = 0; i < keyList.length; i += 1) {
const key = keyList[i];
_url.searchParams.set(keyList[i], params[key]?.toString());
}
}
window.location.assign(_url.href);
} catch (e) {
throw new Error('The URL is not valid');
}
}
};
export default redirectUrl;
If you want a simple way to preserve the query string and possibly append to it, use window.location.search; here's a snippet:
var search = window.location.search + (window.location.search ? "&" : "?");
search += "param1=foo¶m2=bar";
window.location.href = window.location.protocol + "//" + window.location.host + window.location.pathname + search;
You can, of course, use a more sophisticated way of building the rest of your query string, as found in the other examples, but the key is to leverage Location.search.
If you have an existing querystring that you'd like to keep then this version does that and adds your new params to any existing ones. The keys are converted to lowercase so that duplicates are not added. Maintaining the quersytring does make the solution more complicated, so I'd only do this if you need to.
$("#sortby").change(function () {
var queryString = getQueryStrings();
// Add new params to the querystring dictionary
queryString["sortby"] = $("#sortby").val();
window.location.href =
window.location.protocol + "//" +
window.location.host +
window.location.pathname +
createQueryString(queryString);
});
// http://stackoverflow.com/questions/2907482
// Gets Querystring from window.location and converts all keys to lowercase
function getQueryStrings() {
var assoc = {};
var decode = function (s) { return decodeURIComponent(s.replace(/\+/g, " ")); };
var queryString = location.search.substring(1);
var keyValues = queryString.split('&');
for (var i in keyValues) {
var key = keyValues[i].split('=');
if (key.length > 1) {
assoc[decode(key[0]).toLowerCase()] = decode(key[1]);
}
}
return assoc;
}
function createQueryString(queryDict) {
var queryStringBits = [];
for (var key in queryDict) {
if (queryDict.hasOwnProperty(key)) {
queryStringBits.push(key + "=" + queryDict[key]);
}
}
return queryStringBits.length > 0
? "?" + queryStringBits.join("&")
: "";
}
I was having a requirement to open a particular tab after reloading. So I just needed to append the #tabs-4 to the current url. I know its irrelevant to current post but it could help others who come to this just like I did.
Using the code
window.location = window.location.pathname
+ window.location.search + '#tabs-4';
did'nt work for me but below code did.
location = "#tabs-4";
location.reload(true);
I am using jQuery. How do I get the path of the current URL and assign it to a variable?
Example URL:
http://localhost/menuname.de?foo=bar&number=0
To get the path, you can use:
var pathname = window.location.pathname; // Returns path only (/path/example.html)
var url = window.location.href; // Returns full URL (https://example.com/path/example.html)
var origin = window.location.origin; // Returns base URL (https://example.com)
In pure jQuery style:
$(location).attr('href');
The location object also has other properties, like host, hash, protocol, and pathname.
http://www.refulz.com:8082/index.php#tab2?foo=789
Property Result
------------------------------------------
host www.refulz.com:8082
hostname www.refulz.com
port 8082
protocol http:
pathname index.php
href http://www.refulz.com:8082/index.php#tab2
hash #tab2
search ?foo=789
var x = $(location).attr('<property>');
This will work only if you have jQuery. For example:
<html>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
<script>
$(location).attr('href'); // http://www.refulz.com:8082/index.php#tab2
$(location).attr('pathname'); // index.php
</script>
</html>
If you need the hash parameters present in the URL, window.location.href may be a better choice.
window.location.pathname
=> /search
window.location.href
=> www.website.com/search#race_type=1
You'll want to use JavaScript's built-in window.location object.
Just add this function in JavaScript, and it will return the absolute path of the current path.
function getAbsolutePath() {
var loc = window.location;
var pathName = loc.pathname.substring(0, loc.pathname.lastIndexOf('/') + 1);
return loc.href.substring(0, loc.href.length - ((loc.pathname + loc.search + loc.hash).length - pathName.length));
}
I hope it works for you.
window.location is an object in javascript. it returns following data
window.location.host #returns host
window.location.hostname #returns hostname
window.location.path #return path
window.location.href #returns full current url
window.location.port #returns the port
window.location.protocol #returns the protocol
in jquery you can use
$(location).attr('host'); #returns host
$(location).attr('hostname'); #returns hostname
$(location).attr('path'); #returns path
$(location).attr('href'); #returns href
$(location).attr('port'); #returns port
$(location).attr('protocol'); #returns protocol
This is a more complicated issue than many may think. Several browsers support built-in JavaScript location objects and associated parameters/methods accessible through window.location or document.location. However, different flavors of Internet Explorer (6,7) don't support these methods in the same way, (window.location.href? window.location.replace() not supported) so you have to access them differently by writing conditional code all the time to hand-hold Internet Explorer.
So, if you have jQuery available and loaded, you might as well use jQuery (location), as the others mentioned because it resolves these issues. If however, you are doing-for an example-some client-side geolocation redirection via JavaScript (that is, using Google Maps API and location object methods), then you may not want to load the entire jQuery library and write your conditional code that checks every version of Internet Explorer/Firefox/etc.
Internet Explorer makes the front-end coding cat unhappy, but jQuery is a plate of milk.
For the host name only, use:
window.location.hostname
This will also work:
var currentURL = window.location.href;
java-script provides many methods to retrieve current URL which is displayed in browser's address bar.
Test URL :
http://
stackoverflow.com/questions/5515310/get-current-url-with-jquery/32942762
?
rq=1&page=2&tab=active&answertab=votes
#
32942762
resourceAddress.hash();
console.log('URL Object ', webAddress);
console.log('Parameters ', param_values);
Function:
var webAddress = {};
var param_values = {};
var protocol = '';
var resourceAddress = {
fullAddress : function () {
var addressBar = window.location.href;
if ( addressBar != '' && addressBar != 'undefined') {
webAddress[ 'href' ] = addressBar;
}
},
protocol_identifier : function () { resourceAddress.fullAddress();
protocol = window.location.protocol.replace(':', '');
if ( protocol != '' && protocol != 'undefined') {
webAddress[ 'protocol' ] = protocol;
}
},
domain : function () { resourceAddress.protocol_identifier();
var domain = window.location.hostname;
if ( domain != '' && domain != 'undefined' && typeOfVar(domain) === 'string') {
webAddress[ 'domain' ] = domain;
var port = window.location.port;
if ( (port == '' || port == 'undefined') && typeOfVar(port) === 'string') {
if(protocol == 'http') port = '80';
if(protocol == 'https') port = '443';
}
webAddress[ 'port' ] = port;
}
},
pathname : function () { resourceAddress.domain();
var resourcePath = window.location.pathname;
if ( resourcePath != '' && resourcePath != 'undefined') {
webAddress[ 'resourcePath' ] = resourcePath;
}
},
params : function () { resourceAddress.pathname();
var v_args = location.search.substring(1).split("&");
if ( v_args != '' && v_args != 'undefined')
for (var i = 0; i < v_args.length; i++) {
var pair = v_args[i].split("=");
if ( typeOfVar( pair ) === 'array' ) {
param_values[ decodeURIComponent( pair[0] ) ] = decodeURIComponent( pair[1] );
}
}
webAddress[ 'params' ] = param_values;
},
hash : function () { resourceAddress.params();
var fragment = window.location.hash.substring(1);
if ( fragment != '' && fragment != 'undefined')
webAddress[ 'hash' ] = fragment;
}
};
function typeOfVar (obj) {
return {}.toString.call(obj).split(' ')[1].slice(0, -1).toLowerCase();
}
protocol « Web-browsers use Internet Protocol by following some rules for communication between WebHosted Applications and Web Client(Browser). (http = 80, https (SSL) = 443, ftp = 21, etc.)
EX: With default port numbers
<protocol>//<hostname>:<port>/<pathname><search><hash>
https://en.wikipedia.org:443/wiki/Pretty_Good_Privacy
http://stackoverflow.com:80/
(//) « Host is the name given to an end-point(machine on which resource lives) on the Internet.
www.stackoverflow.com - DNS IP Address of an Application (OR) localhost:8080 - localhost
Domain names are which you register by the rules and procedures of the Domain Name System(DNS) tree. DNS servers of someone who manages your domain with IP-Address for addressing purposes. In DNS server hierarchy
the Root name of an stackoverlfow.com is com.
gTLDs - com « stackoverflow (OR) in « co « google
Local system you have to maintain domain's which are not PUBLIC in Host Files.
localhost.yash.com « localhsot - subdomain(web-server), yash.com - maindomain(Proxy-Server).
myLocalApplication.com 172.89.23.777
(/) « The path gives info about the specific resource within the host that the Web client wants to access
(?) « An optional query is to pass a sequence of attribute–value pairs separated by a delimiter(&).
(#) « An optional fragment is often an id attribute of a specific element, and web browsers will scroll this element into view.
If parameter has an Epoch ?date=1467708674 then use.
var epochDate = 1467708674; var date = new Date( epochDate );
URL
Authentication url with username:password, If usernaem/password contains # symbol
like:
Username = `my_email#gmail`
Password = `Yash#777`
then You need to URL encode the # as %40. Refer...
http://my_email%40gmail.com:Yash%40777#www.my_site.com
encodeURI() (vs) encodeURIComponent() example
var testURL = "http:my_email#gmail:Yash777#//stackoverflow.com?tab=active&page=1#32942762";
var Uri = "/:#?&=,#", UriComponent = "$;+", Unescaped = "(-_.!~*')"; // Fixed
var encodeURI_Str = encodeURI(Uri) +' '+ encodeURI( UriComponent ) +' '+ encodeURI(Unescaped);
var encodeURIComponent_Str = encodeURIComponent( Uri ) +' '+ encodeURIComponent( UriComponent ) +' '+ encodeURIComponent( Unescaped );
console.log(encodeURI_Str, '\n', encodeURIComponent_Str);
/*
/:#?&=,# +$; (-_.!~*')
%2F%3A%40%3F%26%3D%2C%23 %2B%24%3B (-_.!~*')
*/
You can log window.location and see all the options, for just the URL use:
window.location.origin
for the whole path use:
window.location.href
there's also location.__
.host
.hostname
.protocol
.pathname
This will return the absolute URL of the current page using JavaScript/jQuery.
document.URL
$("*").context.baseURI
location.href
All browsers support Javascript window object. It defines the window of the browser.
The global objects and functions become part of the window object automatically.
All global variables are window objects properties and all global functions are its methods.
The whole HTML document is a window property too.
So you can use window.location object to get all url related attributes.
Javascript
console.log(window.location.host); //returns host
console.log(window.location.hostname); //returns hostname
console.log(window.location.pathname); //return path
console.log(window.location.href); //returns full current url
console.log(window.location.port); //returns the port
console.log(window.location.protocol) //returns the protocol
JQuery
console.log("host = "+$(location).attr('host'));
console.log("hostname = "+$(location).attr('hostname'));
console.log("pathname = "+$(location).attr('pathname'));
console.log("href = "+$(location).attr('href'));
console.log("port = "+$(location).attr('port'));
console.log("protocol = "+$(location).attr('protocol'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
I have this to strip out the GET variables.
var loc = window.location;
var currentURL = loc.protocol + '//' + loc.host + loc.pathname;
If there is someone who wants to concatenate the URL and hash tag, combine two functions:
var pathname = window.location.pathname + document.location.hash;
You can simply get your path using js itself, window.location or location will give you the object of current URL
console.log("Origin - ",location.origin);
console.log("Entire URL - ",location.href);
console.log("Path Beyond URL - ",location.pathname);
var currenturl = jQuery(location).attr('href');
Here is an example to get the current URL using jQuery and JavaScript:
$(document).ready(function() {
//jQuery
$(location).attr('href');
//Pure JavaScript
var pathname = window.location.pathname;
// To show it in an alert window
alert(window.location);
});
$.getJSON("idcheck.php?callback=?", { url:$(location).attr('href')}, function(json){
//alert(json.message);
});
To get the URL of the parent window from within an iframe:
$(window.parent.location).attr('href');
NB: only works on same domain
The following are examples of useful code snippets that can be used – some of the examples use standard JavaScript functions and are not specific to jQuery:
See 8 Useful jQuery Snippets For URL’s & Querystrings.
var path = location.pathname returns the path of the current URL (jQuery is not needed). The use of window.location is optional.
window.location will give you the current URL, and you can extract whatever you want from it...
If you want to get the path of the root site, use this:
$(location).attr('href').replace($(location).attr('pathname'),'');
Use window.location.href. This will give you the complete URL.
See purl.js. This will really help and can also be used, depending on jQuery. Use it like this:
$.url().param("yourparam");
By the following code you can get the current URL in Jquery.
$(location).attr('hostname'); //origin URL
$(location).attr('pathname'); // path name
$(location).attr('hash'); // everything comes after hash
Very Commonly Used top 3 ones are
1. window.location.hostname
2. window.location.href
3. window.location.pathname
var newURL = window.location.protocol + "//" + window.location.host + "/" + window.location.pathname;
// get current URL
$(location).attr('href');
var pathname = window.location.pathname;
alert(window.location);