Deal with query strings in JS, like http_build_query, etc - javascript

Here's what I have
if(condition1) {
location.href = location.href+'/?site_type=normal';
}
else if(condition2) {
location.href = location.href+'/?site_type=other';
}
Of course, if the location.href already has query vars on it, thats a problem, etc.
I need to
Find the vars from the query string
if site_type already exists, replace the value with either 'normal' or 'other'
rebuild the url with the new site_type
edit:
I found I needed to account for all kinds of URLs:
domain.com
domain.com/path/to/sth/
domain.com/?site_type=normal
domain.com?var=123&foo=987
domain.com/path/?site_type=normal&var=123&foo=987
So, here's what I came up with, suggestions welcome:
var searchstring = window.location.search;
var url = window.location.href;
console.log('search: ' + searchstring);
console.log( 'url: ' + url);
// strip search from url
url = url.replace(searchstring,"");
console.log( 'url: ' + url);
//strip site_type from search
searchstring = searchstring.replace("&site_type=normal","")
.replace("&site_type=other","")
.replace("?site_type=normal","")
.replace("?site_type=other","")
.replace("?","")
;
console.log('search: ' + searchstring);
if(searchstring != ''){searchstring = '&' + searchstring;}
var final = url + '?site_type=normal' + searchstring;
final = final.replace("&&","&");
console.log('final: ' + final);

You can directly access the query string with window.location.search. You can convert it to an object using this regex trick found here.
var queryString = {};
window.location.search.replace(/([^?=&]+)(=([^&]*))?/g, function($0, $1, $2, $3) {
queryString[$1] = $3; }
);
Then set the site_type on queryString appropriately.
queryString["site_type"] = "normal";
And finally, convert it back into a string and set that as the window.location.search.
var searchString = "";
for ( q in queryString ) {
searchString+="&" + q + "=" + queryString[q];
}
window.location.search = searchString;

Here's a way to do this:
//remove existing param and append new one..
var newHref = window.location.href.replace(window.location.search,"") + '?site_type=other';
//change href
window.location.href = newHref;
works only if you have one parameter that you want to replace, otherwise it would remove all parameters.

for example if you have
yourpage.com/?site_type=normal
and you need only website not query vars you cans clear them
var novars= location.href.replace(window.location.search,"")
this case novars = youroage.com
for just getting variables u can do this:
var site_type = window.location.search.replace("?site_type=","");
here i will get site_type value whether its normal or other
this case your variable site_type = "normal"
for rebuilding url u can just add new site_type
location.href = novars+"?site_type=normal"
or
location.href = novars+"?site_type=other"

Related

Add new Param URL in the middle using javascript

Sorry for asking simple questions.
I have url with like this :
http://sub.maindomain/page/title
I want to add
/en/
in the middle of my url so it will be change to
http://sub.maindomain/en/page/title
thank you for your help
var str='http://sub.maindomain/page/title';
var en='en/';
var position= str.indexOf('page')
alert(str.substr(0, position) + en + str.substr(position));
i guess there will be always page in that url so i found it's index,
and added en before it's index
If you want to change the actual URL with a new URL parameter en in the address bar. You can try this.
var newUrl = location.origin + '/en' + location.pathname
document.location.href = newUrl
Supposing you're in a context where document is available (since your post is taggued jQuery, it's most likely the case):
const href = 'http://sub.maindomain/page/title?foo=bar#hash';
// Build a link element
const link = document.createElement('a');
link.href = href;
// Add '/en' before its pathname
const result = link.protocol + '//' + link.host + '/en' + link.pathname + link.search + link.hash;
console.log(result);
in case if page is not on after domain some other string is there then try below code.
var str = 'http://sub.maindomain/page/title';
var arr = str.split(/\//);
arr.splice(3, 0, 'en');
str = arr.join('/');
let url = "http://sub.maindomain/page/title";
let textToAdd = "en/";
//Split the url string into array of two elements and then join them together with a new string 'en/page' as a separator
let newUrl = url.split('page').join(`${textToAdd}page`);
console.log(newUrl);

Update uri hash javascript

I find it hard to believe this hasn't been asked but I can find no references anywhere. I need to add a URI hash fragment and update the value if it already is in the hash. I can currently get it to add the hash but my regex doesn't appear to catch if it exists so it adds another instead of updating.
setQueryString : function() {
var value = currentPage;
var uri = window.location.hash;
var key = "page";
var re = new RegExp("([#&])" + key + "=.*#(&|$)", "i");
var separator = uri.indexOf('#') !== -1 ? "&" : "#";
if (uri.match(re)) {
return uri.replace(re, '$1' + key + "=" + value + '$2');
}
else {
return uri + separator + key + "=" + value;
}
},
Also if this can be made any cleaner while preserving other url values/hashes that would be great.
example input as requested
Starting uri value:
www.example.com#page=1 (or no #page at all)
then on click of "next page" setQueryString gets called so the values would equal:
var value = 2;
var uri = '#page1'
var key = 'page'
So the hopeful output would be '#page2'.
As to your regex question, testing if the pattern #page=(number) or &page=(number) is present combined with capturing the number, can be done with the regex /[#&]page\=(\d*)/ and the .match(regex) method. Note that = needs escaping in regexes.
If the pattern exists in the string, result will contain an array with the integer (as a string) at result[1]. If the pattern does not exist, result will be null.
//match #page=(integer) or &page=(integer)
var test = "#foo=bar&page=1";
var regex = /[#&]page\=(\d*)/;
var result = test.match(regex);
console.log(result);
If you want to dynamically set the key= to something other than "page", you could build the regex dynamically, like the following (note that backslashes needs escaping in strings, making the code a bit more convoluted):
//dynamically created regex
var test = "#foo=bar&page=1";
var key = "page"
var regex = new RegExp("[#&]" + key + "\\=(\\d*)");
var result = test.match(regex);
console.log(result);

Javascript: Using variables from current URL to create and open new URL

I have got a current URL looking like this:
http://example?variables1=xxxx&example&variables2=yyyyy
I want to use the variables1 and variables2 to create a new URL and open this new URL:
http://example?variables3=variables1&example&variables4=variables2
I hope someone can help me with this :)
You will need to parse the desired query parameters from the first URL and use string addition to create the second URL.
You can fetch a specific query parameter from the URL using this code. If you were using that, you could get variables1 and variables2 like this:
var variables1 = getParameterByName("variables1");
var variables2 = getParameterByName("variables2");
You could then use those to construct your new URL.
newURL = "http://example.com/?variables1=" +
encodeURIComponent(variables1) +
"&someOtherStuff=foo&variables2=" +
encodeURIComponent(variables2);
Because I don't fully understand what needs to change, here's my best attempt*, using a mashup of other answers and resources online.
// the original url
// will most likely be window.location.href
var original = "http://example?variables1=xxxx&example&variables2=yyyyy";
// the function to pull vals from the URL
var getParameterByName = function(name, uri) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(uri);
if(results == null) return "";
else return decodeURIComponent(results[1].replace(/\+/g, " "));
};
// so, to get the vals from the URL
var variables1 = getParameterByName('variables1', original); // xxxxx
var variables2 = getParameterByName('variables2', original); // yyyyy
// then to construct the new URL
var newURL = "http://" + window.location.host;
newURL += "?" + "variables3=" + variables1;
newURL += "&example&"; // I don't know what this is ...
newURL += "variables4=" + variables2;
// the value should be something along the lines of
// http://example?variables3=xxxx&example&variables4=yyyy
​
*All of which is untested.

Passing URL using javascript

Suppose that I have a URL like the following:
http://localhost:8000/intranet/users/view?user_id=8823
Now, all I want to do is to get the value of the URL using JavaScript and parse it, taking the user_id value (which is 8823 in this case) and sending that value through an iframe.
How can I do this?
try this code
function getParameterByName(name)
{
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);
if(results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
i found it at How can I get query string values in JavaScript?
Try using window.location.href or document.URL
Do this:
var matches = document.location.search.match( /user_id=(\d+)/ );
if ( matches != null )
{
alert( matches[ 1 ] );
}
matches[ 1 ] will contain the user ID.
document.location.search contains the query string (all of the parameters which follow the '?' including the '?').
var test = "http://localhost:8000/intranet/users/view?user_id=8823";
//var url = document.URL;
var url = test.split("=");
var urlID = url[url.length-1];
document.write(urlID);
window.frames["myIframe"].yourMethod(urlID);

Adding/Modify query string / GET variables in a url with javascript

So I am wanting to replace GET variable values in a url and if the variable does not exist, then add it to the url.
EDIT: I am doing this to a elements href not the pages current location..
I am not good with javascript but I do know how to use jQuery quite well and the basics of javascript. I do know how to write regex but not how to use the javascript syntax of regex and what functions to use it with.
Here is what I have so far and it does have an error on line 3: See it on jsfiddle(or below): http://jsfiddle.net/MadLittleMods/C93mD/
function addParameter(url, param, value) {
var pattern = new RegExp(param + '=(.*?);', 'gi');
return url.replace(pattern, param + '=' + value + ';');
alert(url);
}
No need to use jQuery on this one. Regular Expressions and string functions are sufficient. See my commented code below:
function addParameter(url, param, value) {
// Using a positive lookahead (?=\=) to find the
// given parameter, preceded by a ? or &, and followed
// by a = with a value after than (using a non-greedy selector)
// and then followed by a & or the end of the string
var val = new RegExp('(\\?|\\&)' + param + '=.*?(?=(&|$))'),
parts = url.toString().split('#'),
url = parts[0],
hash = parts[1]
qstring = /\?.+$/,
newURL = url;
// Check if the parameter exists
if (val.test(url))
{
// if it does, replace it, using the captured group
// to determine & or ? at the beginning
newURL = url.replace(val, '$1' + param + '=' + value);
}
else if (qstring.test(url))
{
// otherwise, if there is a query string at all
// add the param to the end of it
newURL = url + '&' + param + '=' + value;
}
else
{
// if there's no query string, add one
newURL = url + '?' + param + '=' + value;
}
if (hash)
{
newURL += '#' + hash;
}
return newURL;
}
And here is the Fiddle
Update:
The code now handles the case where there is a hash on the URL.
Edit
Missed a case! The code now checks to see if there is a query string at all.
I would go with this small but complete library to handle urls in js:
https://github.com/Mikhus/jsurl
See Change URL parameters. It answers your question in a more general manner (changing any url parameter). There are solutions for both jQuery and regular js in the answers section.
It also looks like url.replace should be location.replace but I may be wrong (that statement's based on a quick google search for 'url.replace javascript').
<script type="text/javascript">
$(document).ready(function () {
$('input.letter').click(function () {
//0- prepare values
var qsTargeted = 'letter=' + this.value; //"letter=A";
var windowUrl = '';
var qskey = qsTargeted.split('=')[0];
var qsvalue = qsTargeted.split('=')[1];
//1- get row url
var originalURL = window.location.href;
//2- get query string part, and url
if (originalURL.split('?').length > 1) //qs is exists
{
windowUrl = originalURL.split('?')[0];
var qs = originalURL.split('?')[1];
//3- get list of query strings
var qsArray = qs.split('&');
var flag = false;
//4- try to find query string key
for (var i = 0; i < qsArray.length; i++) {
if (qsArray[i].split('=').length > 0) {
if (qskey == qsArray[i].split('=')[0]) {
//exists key
qsArray[i] = qskey + '=' + qsvalue;
flag = true;
break;
}
}
}
if (!flag)// //5- if exists modify,else add
{
qsArray.push(qsTargeted);
}
var finalQs = qsArray.join('&');
//6- prepare final url
window.location = windowUrl + '?' + finalQs;
}
else {
//6- prepare final url
//add query string
window.location = originalURL + '?' + qsTargeted;
}
})
});
</script>

Categories