How can I change the value of a querystring with mooTools? - javascript

Given a string containing an absolute URL with a querystring parameter, what is the easiest way to replace the value of the parameter using JavaScript and/or MooTools?
e.g.
// Change this
'/foo/bar?frob=123456789'
// Into this
'/foo/bar?frob=abcdefg'
EDIT
The URL is not the location of the current window. It is a variable containing a string. I just want to manipulate this string.

Further to what you did, this may be better as it will extend String and it removes dependency on URI class...
(function() {
// deps on Types/String.toQueryString()
String.implement({
fixQueryString: function(key, value) {
var query = this.parseQueryString() || {};
query[key] = value;
return Object.toQueryString(query);
}
});
// exports:
this.replaceUrlParameter = function(url, key, value) {
var parts = url.split('?'), QS = parts[1] || null;
return QS ? [parts[0], QS.fixQueryString(key, value)].join("?") : url;
};
})();
console.log(replaceUrlParameter('/foo/bar', 'frob', 'ownies'));
/foo/bar/
console.log(replaceUrlParameter('/foo/bar?frob=123123123', 'frob', 'ownies'));
/foo/bar?frob=ownies
http://jsfiddle.net/dimitar/fjj6W/

Sorry for bumping an old post but I think it's already in mootools. No need to write it yourself :-) http://mootools.net/docs/more/Types/URI#URI:setData
Or take a look here if your on a very old version of mootools: http://pilon.nl/mootools/2009/02/05/extra-browsersextras/

If You want to do this without reloading the page, there is no way (this is part of the web browser security model).
If You don't mind reloading the page, consider:
location.href='http://example.com/foo/bar?frob=baz'
An alternative without reloading is using location.hash, i.e.
location.hash = 'myhash'
to change url to http://example.com/foo/bar?frob=123456789#myhash
This is the basis of the Hash bang urls

This is the solution I came up with. This is dependent on MooTools.
function replaceUrlParameter (url, parameterName, newValue) {
var uri = new URI(url);
var uriBase = ri.get('directory') + uri.get('file');
var query = uri.get('query').parseQueryString(false, true);
query[parameterName] = newValue;
uriBase += '?';
for (var i in query) {
if (i === 'undefined') continue;
if (i === '') continue;
uriBase += i + '=' + escape(query[i]) + '&';
}
return uriBase.substring(0, galleryLinkBase.length - 1);
}
This is specific to my usage but it might serve as a starting point for others in the future.

Related

Getting URL parameters and filter out a specific parameter

I want to filter out a specific parameter out of the URL. I have the following situation:
The page got loaded (for example: http://test.com/default.aspx?folder=app&test=true)
When the page is loaded a function is called to push a entry to the history (pushState): ( for example: http://test.com/default.aspx?folder=app&test=true&state=1)
Now I want to call a function that reads all the parameters and output all these parameters expect for the state. So that I end up with: "?folder=app&test=true" (just a string value, no array or object). Please keep in mind that I do not know what all the names of the parameters are execpt for the state parameter
What I have tried
I know I can get all the parameters by using the following code:
window.location.search
But it will result in:
?folder=app&test=true&state=1
I try to split the url, for example:
var url = '?folder=app&test=true&state=1';
url = url.split('&state=');
console.log(url);
But that does not work. Also because the state number is dynamic in each request. A solution might be remove the last parameter out of the url but I also do not know if that ever will be the case therefore I need some filtering mechanisme that will only filter out the
state=/*regex for a number*/
To achieve this you can convert the querystring provided to the page to an object, remove the state property of the result - assuming it exists - then you can convert the object back to a querystring ready to use in pushState(). Something like this:
var qsToObj = function(qs) {
qs = qs.substring(1);
if (!qs) return {};
return qs.split("&").reduce(function(prev, curr, i, arr) {
var p = curr.split("=");
prev[decodeURIComponent(p[0])] = decodeURIComponent(p[1]);
return prev;
}, {});
}
var qs = '?'; // window.location.search;
var obj = qsToObj(qs);
delete obj.state;
console.log(obj);
var newQs = $.param(obj);
console.log(newQs);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Credit to this answer for the querystring to object logic.
I would agree with Rory's answer, you should have an object to safely manipulate params. This is the function that I use.
function urlParamsObj(source) {
/* function returns an object with url parameters
URL sample: www.test.com?var1=value1&var2=value2
USE: var params = URLparamsObj();
alert(params.var2) --> output: value2
You can use it for a url-like string also: urlParamsObj("www.ok.uk?a=2&b=3")*/
var urlStr = source ? source : window.location.search ? window.location.search : ""
if (urlStr.indexOf("?") > -1) { // if there are params in URL
var param_array = urlStr.substring(urlStr.indexOf("?") + 1).split('&'),
theLength = param_array.length,
params = {},
i = 0,
x;
for (; i < theLength; i++) {
x = param_array[i].toString().split('=');
params[x[0]] = x[1];
}
return params;
}
return {};
}
A much simpler way to do this would be:
let url = new URL(window.location.href)
url.searchParams.delete('state');
window.location.search = url.search;
You can read about URLSearchParams.delete() in the MDN Web Docs.
Sorry if this is wrong just as i think &state=1,2,3,4,5,6 is absolute its just depends on number to pick states just like my web
var url = '?folder=app&test=true&state=1';
url = url.substring(0, url.indexOf('&s'));
$('#demo').text(url);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id='demo'></span>
var url = '?folder=app&test=true&state=1';
url = url.split('&folder=');
console.log(url);

Get Query String with Dojo

Users will be hitting up against a URL that contains a query string called inquirytype. For a number of reasons, I need to read in this query string with javascript (Dojo) and save its value to a variable. I've done a fair amount of research trying to find how to do this, and I've discovered a few possibilities, but none of them seem to actually read in a query string that isn't hard-coded somewhere in the script.
You can access parameters from the url using location.search without Dojo Can a javascript attribute value be determined by a manual url parameter?
function getUrlParams() {
var paramMap = {};
if (location.search.length == 0) {
return paramMap;
}
var parts = location.search.substring(1).split("&");
for (var i = 0; i < parts.length; i ++) {
var component = parts[i].split("=");
paramMap [decodeURIComponent(component[0])] = decodeURIComponent(component[1]);
}
return paramMap;
}
Then you could do the following to extract id from the url /hello.php?id=5&name=value
var params = getUrlParams();
var id = params['id']; // or params.id
Dojo provides http://dojotoolkit.org/reference-guide/dojo/queryToObject.html which is a bit smarter than my simple implementation and creates arrays out of duplicated keys.
var uri = "http://some.server.org/somecontext/?foo=bar&foo=bar2&bit=byte";
var query = uri.substring(uri.indexOf("?") + 1, uri.length);
var queryObject = dojo.queryToObject(query);
//The structure of queryObject will be:
// {
// foo: ["bar", "bar2],
// bit: "byte"
// }
In new dojo it's accessed with io-query:
require([
"dojo/io-query",
], function (ioQuery) {
GET = ioQuery.queryToObject(decodeURIComponent(dojo.doc.location.search.slice(1)));
console.log(GET.id);
});
Since dojo 0.9, there is a better option, queryToObject.
dojo.queryToObject(query)
See this similar question with what I think is a cleaner answer.

Get escaped URL parameter

I'm looking for a jQuery plugin that can get URL parameters, and support this search string without outputting the JavaScript error: "malformed URI sequence". If there isn't a jQuery plugin that supports this, I need to know how to modify it to support this.
?search=%E6%F8%E5
The value of the URL parameter, when decoded, should be:
æøå
(the characters are Norwegian).
I don't have access to the server, so I can't modify anything on it.
function getURLParameter(name) {
return decodeURI(
(RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
);
}
Below is what I have created from the comments here, as well as fixing bugs not mentioned (such as actually returning null, and not 'null'):
function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null;
}
What you really want is the jQuery URL Parser plugin. With this plugin, getting the value of a specific URL parameter (for the current URL) looks like this:
$.url().param('foo');
If you want an object with parameter names as keys and parameter values as values, you'd just call param() without an argument, like this:
$.url().param();
This library also works with other urls, not just the current one:
$.url('http://allmarkedup.com?sky=blue&grass=green').param();
$('#myElement').url().param(); // works with elements that have 'src', 'href' or 'action' attributes
Since this is an entire URL parsing library, you can also get other information from the URL, like the port specified, or the path, protocol etc:
var url = $.url('http://allmarkedup.com/folder/dir/index.html?item=value');
url.attr('protocol'); // returns 'http'
url.attr('path'); // returns '/folder/dir/index.html'
It has other features as well, check out its homepage for more docs and examples.
Instead of writing your own URI parser for this specific purpose that kinda works in most cases, use an actual URI parser. Depending on the answer, code from other answers can return 'null' instead of null, doesn't work with empty parameters (?foo=&bar=x), can't parse and return all parameters at once, repeats the work if you repeatedly query the URL for parameters etc.
Use an actual URI parser, don't invent your own.
For those averse to jQuery, there's a version of the plugin that's pure JS.
If you don't know what the URL parameters will be and want to get an object with the keys and values that are in the parameters, you can use this:
function getParameters() {
var searchString = window.location.search.substring(1),
params = searchString.split("&"),
hash = {};
if (searchString == "") return {};
for (var i = 0; i < params.length; i++) {
var val = params[i].split("=");
hash[unescape(val[0])] = unescape(val[1]);
}
return hash;
}
Calling getParameters() with a url like /posts?date=9/10/11&author=nilbus would return:
{
date: '9/10/11',
author: 'nilbus'
}
I won't include the code here since it's even farther away from the question, but weareon.net posted a library that allows manipulation of the parameters in the URL too:
Blog post: http://blog.weareon.net/working-with-url-parameters-in-javascript/
Code: http://pastebin.ubuntu.com/1163515/
You can use the browser native location.search property:
function getParameter(paramName) {
var searchString = window.location.search.substring(1),
i, val, params = searchString.split("&");
for (i=0;i<params.length;i++) {
val = params[i].split("=");
if (val[0] == paramName) {
return unescape(val[1]);
}
}
return null;
}
But there are some jQuery plugins that can help you:
query-object
getURLParam
Based on the 999's answer:
function getURLParameter(name) {
return decodeURIComponent(
(location.search.match(RegExp("[?|&]"+name+'=(.+?)(&|$)'))||[,null])[1]
);
}
Changes:
decodeURI() is replaced with decodeURIComponent()
[?|&] is added at the beginning of the regexp
Need to add the i parameter to make it case insensitive:
function getURLParameter(name) {
return decodeURIComponent(
(RegExp(name + '=' + '(.+?)(&|$)', 'i').exec(location.search) || [, ""])[1]
);
}
After reading all of the answers I ended up with this version with + a second function to use parameters as flags
function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)','i').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null;
}
function isSetURLParameter(name) {
return (new RegExp('[?|&]' + name + '(?:[=|&|#|;|]|$)','i').exec(location.search) !== null)
}
$.urlParam = function(name){
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(top.window.location.href);
return (results !== null) ? results[1] : 0;
}
$.urlParam("key");
For example , a function which returns value of any parameters variable.
function GetURLParameter(sParam)
{
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam)
{
return sParameterName[1];
}
}
}​
And this is how you can use this function assuming the URL is,
"http://example.com/?technology=jquery&blog=jquerybyexample".
var tech = GetURLParameter('technology');
var blog = GetURLParameter('blog');
So in above code variable "tech" will have "jQuery" as value and "blog" variable's will be "jquerybyexample".
You should not use jQuery for something like this!
The modern way is to use small reusable modules through a package-manager like Bower.
I've created a tiny module that can parse the query string into an object. Use it like this:
// parse the query string into an object and get the property
queryString.parse(unescape(location.search)).search;
//=> æøå
There's a lot of buggy code here and regex solutions are very slow. I found a solution that works up to 20x faster than the regex counterpart and is elegantly simple:
/*
* #param string parameter to return the value of.
* #return string value of chosen parameter, if found.
*/
function get_param(return_this)
{
return_this = return_this.replace(/\?/ig, "").replace(/=/ig, ""); // Globally replace illegal chars.
var url = window.location.href; // Get the URL.
var parameters = url.substring(url.indexOf("?") + 1).split("&"); // Split by "param=value".
var params = []; // Array to store individual values.
for(var i = 0; i < parameters.length; i++)
if(parameters[i].search(return_this + "=") != -1)
return parameters[i].substring(parameters[i].indexOf("=") + 1).split("+");
return "Parameter not found";
}
console.log(get_param("parameterName"));
Regex is not the be-all and end-all solution, for this type of problem simple string manipulation can work a huge amount more efficiently. Code source.
<script type="text/javascript">
function getURLParameter(name) {
return decodeURIComponent(
(location.search.toLowerCase().match(RegExp("[?|&]" + name + '=(.+?)(&|$)')) || [, null])[1]
);
}
</script>
getURLParameter(id) or getURLParameter(Id) Works the same : )
jQuery code snippet to get the dynamic variables stored in the url as parameters and store them as JavaScript variables ready for use with your scripts:
$.urlParam = function(name){
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (results==null){
return null;
}
else{
return results[1] || 0;
}
}
example.com?param1=name&param2=&id=6
$.urlParam('param1'); // name
$.urlParam('id'); // 6
$.urlParam('param2'); // null
//example params with spaces
http://www.jquery4u.com?city=Gold Coast
console.log($.urlParam('city'));
//output: Gold%20Coast
console.log(decodeURIComponent($.urlParam('city')));
//output: Gold Coast
function getURLParameters(paramName)
{
var sURL = window.document.URL.toString();
if (sURL.indexOf("?") > 0)
{
var arrParams = sURL.split("?");
var arrURLParams = arrParams[1].split("&");
var arrParamNames = new Array(arrURLParams.length);
var arrParamValues = new Array(arrURLParams.length);
var i = 0;
for (i=0;i<arrURLParams.length;i++)
{
var sParam = arrURLParams[i].split("=");
arrParamNames[i] = sParam[0];
if (sParam[1] != "")
arrParamValues[i] = unescape(sParam[1]);
else
arrParamValues[i] = "No Value";
}
for (i=0;i<arrURLParams.length;i++)
{
if(arrParamNames[i] == paramName){
//alert("Param:"+arrParamValues[i]);
return arrParamValues[i];
}
}
return "No Parameters Found";
}
}
I created a simple function to get URL parameter in JavaScript from a URL like this:
.....58e/web/viewer.html?page=*17*&getinfo=33
function buildLinkb(param) {
var val = document.URL;
var url = val.substr(val.indexOf(param))
var n=parseInt(url.replace(param+"=",""));
alert(n+1);
}
buildLinkb("page");
OUTPUT: 18
Just in case you guys have the url like localhost/index.xsp?a=1#something and you need to get the param not the hash.
var vars = [], hash, anchor;
var q = document.URL.split('?')[1];
if(q != undefined){
q = q.split('&');
for(var i = 0; i < q.length; i++){
hash = q[i].split('=');
anchor = hash[1].split('#');
vars.push(anchor[0]);
vars[hash[0]] = anchor[0];
}
}
Slight modification to the answer by #pauloppenheim , as it will not properly handle parameter names which can be a part of other parameter names.
Eg: If you have "appenv" & "env" parameters, redeaing the value for "env" can pick-up "appenv" value.
Fix:
var urlParamVal = function (name) {
var result = RegExp("(&|\\?)" + name + "=(.+?)(&|$)").exec(location.search);
return result ? decodeURIComponent(result[2]) : "";
};
This may help.
<script type="text/javascript">
$(document).ready(function(){
alert(getParameterByName("third"));
});
function getParameterByName(name){
var url = document.URL,
count = url.indexOf(name);
sub = url.substring(count);
amper = sub.indexOf("&");
if(amper == "-1"){
var param = sub.split("=");
return param[1];
}else{
var param = sub.substr(0,amper).split("=");
return param[1];
}
}
</script>

Accessing CGI values with Prototype

Anyone know the quickest way to grab the value of a CGI variable in the current URL using Prototype? So if I get redirected to a page with the following URL:
http://mysite.com/content?x=foobar
I am interested in retrieving the value of "x" (should be "foobar") in a function called on page load like this:
Event.observe(window, "load", my_fxn ());
Thanks
You may want to look at the parseQuery method. This should do all the splitting you'd expect on a standard querystring such as document.location.search
http://api.prototypejs.org/language/string.html#parsequery-instance_method
For example:
document.location.search.parseQuery()["x"];
Will be undefined if it's not present, and should be the value otherwise.
I couldn't find any shortcuts here, so in the end I just parsed the URL with js like so:
function my_fxn () {
var varsFromUrl = document.location.search;
// get rid of first char '?'
varsFromUrl = varsFromUrl.substring(1);
var pairsArray = varsFromUrl.split("&");
for (i = 0; i < pairsArray.length; i++) {
var pair = pairsArray[i].split("=");
if (pair[0] == "x")
alert(pair[1] + ' is what I want.');
}
}

How to get "GET" request parameters in JavaScript? [duplicate]

This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 1 year ago.
How to get "GET" variables from request in JavaScript?
Does jQuery or YUI! have this feature built-in?
Update June 2021:
Today's browsers have built-in APIs for working with URLs (URL) and query strings (URLSearchParams) and these should be preferred, unless you need to support some old browsers or Opera mini (Browser support).
Original:
All data is available under
window.location.search
you have to parse the string, eg.
function get(name){
if(name=(new RegExp('[?&]'+encodeURIComponent(name)+'=([^&]*)')).exec(location.search))
return decodeURIComponent(name[1]);
}
just call the function with GET variable name as parameter, eg.
get('foo');
this function will return the variables value or undefined if variable has no value or doesn't exist
You could use jquery.url I did like this:
var xyz = jQuery.url.param("param_in_url");
Check the source code
Updated Source: https://github.com/allmarkedup/jQuery-URL-Parser
try the below code, it will help you get the GET parameters from url .
for more details.
var url_string = window.location.href; // www.test.com?filename=test
var url = new URL(url_string);
var paramValue = url.searchParams.get("filename");
alert(paramValue)
Just to put my two cents in, if you wanted an object containing all the requests
function getRequests() {
var s1 = location.search.substring(1, location.search.length).split('&'),
r = {}, s2, i;
for (i = 0; i < s1.length; i += 1) {
s2 = s1[i].split('=');
r[decodeURIComponent(s2[0]).toLowerCase()] = decodeURIComponent(s2[1]);
}
return r;
};
var QueryString = getRequests();
//if url === "index.html?test1=t1&test2=t2&test3=t3"
console.log(QueryString["test1"]); //logs t1
console.log(QueryString["test2"]); //logs t2
console.log(QueryString["test3"]); //logs t3
Note, the key for each get param is set to lower case. So, I made a helper function. So now it's case-insensitive.
function Request(name){
return QueryString[name.toLowerCase()];
}
Unlike other answers, the UrlSearchParams object can avoid using Regexes or other string manipulation and is available is most modern browsers:
var queryString = location.search
let params = new URLSearchParams(queryString)
// example of retrieving 'id' parameter
let id = parseInt(params.get("id"))
console.log(id)
You can use the URL to acquire the GET variables. In particular, window.location.search gives everything after (and including) the '?'. You can read more about window.location here.
A map-reduce solution:
var urlParams = location.search.split(/[?&]/).slice(1).map(function(paramPair) {
return paramPair.split(/=(.+)?/).slice(0, 2);
}).reduce(function (obj, pairArray) {
obj[pairArray[0]] = pairArray[1];
return obj;
}, {});
Usage:
For url: http://example.com?one=1&two=2
console.log(urlParams.one) // 1
console.log(urlParams.two) // 2
Today I needed to get the page's request parameters into a associative array so I put together the following, with a little help from my friends. It also handles parameters without an = as true.
With an example:
// URL: http://www.example.com/test.php?abc=123&def&xyz=&something%20else
var _GET = (function() {
var _get = {};
var re = /[?&]([^=&]+)(=?)([^&]*)/g;
while (m = re.exec(location.search))
_get[decodeURIComponent(m[1])] = (m[2] == '=' ? decodeURIComponent(m[3]) : true);
return _get;
})();
console.log(_GET);
> Object {abc: "123", def: true, xyz: "", something else: true}
console.log(_GET['something else']);
> true
console.log(_GET.abc);
> 123
You can parse the URL of the current page to obtain the GET parameters. The URL can be found by using location.href.
If you already use jquery there is a jquery plugin that handles this:
http://plugins.jquery.com/project/query-object
The function here returns the parameter by name. With tiny changes you will be able to return base url, parameter or anchor.
function getUrlParameter(name) {
var urlOld = window.location.href.split('?');
urlOld[1] = urlOld[1] || '';
var urlBase = urlOld[0];
var urlQuery = urlOld[1].split('#');
urlQuery[1] = urlQuery[1] || '';
var parametersString = urlQuery[0].split('&');
if (parametersString.length === 1 && parametersString[0] === '') {
parametersString = [];
}
// console.log(parametersString);
var anchor = urlQuery[1] || '';
var urlParameters = {};
jQuery.each(parametersString, function (idx, parameterString) {
paramName = parameterString.split('=')[0];
paramValue = parameterString.split('=')[1];
urlParameters[paramName] = paramValue;
});
return urlParameters[name];
}
Works for me in
url: http://localhost:8080/#/?access_token=111
function get(name){
const parts = window.location.href.split('?');
if (parts.length > 1) {
name = encodeURIComponent(name);
const params = parts[1].split('&');
const found = params.filter(el => (el.split('=')[0] === name) && el);
if (found.length) return decodeURIComponent(found[0].split('=')[1]);
}
}

Categories