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.
Related
I have a language selector dropdown in my site.
On change of the language the URL redirects to the respective site
My Current URL is
https://www.example.com/mem/ca/en/pages/home.aspx
On change of the language, the URL should be like
https://www.example.com/mem/ca/en/pages/home.aspx - on selecting english
https://www.example.com/mem/ca/el/pages/home.aspx - on selecting Español
https://www.example.com/mem/ca/py/pages/home.aspx - on selecting Pусский and so on for all the languages
<pre>
$("#dd-language").on("change", function() {
var countryAppend = $(this).val();
var pathArray = window.location.pathname.split('/')[4];
var res = pathArray.replace(pathArray,countryAppend);
var newURL = window.location.host + "/" + pathArray;
window.location = newURL;
});
</pre>
This adds the value at the end of the URL but I need it to replace the language code in the URL
Once you have the array of the pathname split by /, overwrite the [2]nd item in the array with the new language, then join by /s again:
$("#dd-language").on("change", function() {
var countryAppend = $(this).val();
var pathArray = window.location.pathname.split('/');
pathArray[2] = countryAppend;
var newURL = window.location.host + pathArray.join('/');
window.location = newURL;
});
Eg, for
/mem/ca/en/pages/home.aspx
On splitting by /, the 2nd item in the array will be the ca:
const pathArr = '/mem/ca/en/pages/home.aspx'.split('/');
pathArr[2] = 'el';
console.log(pathArr.join('/'));
so reassigning that array item and then joining results in the desired output.
document.querySelector('#dd-language').addEventListener('change',function(){
let url = window.location.href.split('/');
url[5] = this.value;
url = url.join('/');
window.location = url;
});
A regular expression should be useful here
$("#dd-language").on("change", function() {
var countryAppend = $(this).val();
var url = location.href;
window.location = url.replace(/\/.{2}\/pages/,"/"+countryAppend+"/pages");
});
Example
countryAppend ="xx"
console.log(
`https://www.example.com/mem/ca/en/pages/home.aspx`.replace(/\/.{2}\/pages/,"/"+countryAppend+"/pages"),
`https://www.example.com/mem/us/el/pages/home.aspx`.replace(/\/.{2}\/pages/,"/"+countryAppend+"/pages"),
`https://www.example.com/mem/mx/py/pages/home.aspx`.replace(/\/.{2}\/pages/,"/"+countryAppend+"/pages")
)
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);
For example:
example.com/fun/browse/apples/bananas
example.com/browse/gerbals/cooties
How can I find the keyword "browse", regardless of where it is in the url, and remove the following url part. In the above cases that would be "apples" and "gerbals"
I tried spliting it by the "/" and getting the indexOf browse, then removing the next item, but I cant seem to join everything together because that creates a double "//" in the new url.
Any help would be appreciated.
Javascript and jQuery both ok.
NOTE: I do not want to remove any other part of the url. I want to keep everything. I want to only remove the part of the url immediately after browse.
Your question is unclear but let's try :
var s = 'example.com/fun/browse/apples/bananas';
s.replace(/(\/browse)\/[^\/]+/, '$1'); // "example.com/fun/browse/bananas"
Also check this helper :
function removeAfter(s, keyword) {
return s.replace(
new RegExp('(\/' + keyword + ')\/[^\/]+'), '$1'
);
}
Usage :
var s = 'example.com/browse/gerbals/cooties';
removeAfter(s, 'browse'); // "example.com/browse/cooties"
removeAfter(s, 'gerbals'); // "example.com/browse/gerbals"
Demo : http://jsfiddle.net/wared/VRJtL/.
remove browser by using .splice() & rejoin it.
var arr = "example.com/fun/browse/apples/bananas".split('/');
var index = arr.indexOf("browse");
arr.splice(index+1,1); //removes apples
var URL = arr.join('/'); //joins back
result: "example.com/fun/browse/bananas"
Split the URL on the Keyword...
example:
var url = "http://www.foo.com/bar/alpha/beta";
var keyword = "alpha";
var result = url.split(keyword)[0];
//result = "http://www.foo.com/bar/" + keyword;
//adding the keyword is if you need the keyword in your response.
If you're not trying to remove 'fun' part, it's really simple:
var url = 'example.com/fun/browse/apples/bananas';
var result = url.replace(/browse\/[a-zA-Z\/]+/, 'browse/gerbals/cooties');
I'll throw out another option, just to make it interesting. :)
var url = "http://example.com/fun/browse/apples/bananas";
var targetWord = "browse";
var regexPattern = new RegExp("(^.*" + targetWord + "/?)[^/]*/?(.*$)");
var newURL = "";
var matchedURLparts = regexPattern.exec(url);
if (matchedURLparts) {
newURL = (matchedURLparts.length > 2) ? matchedURLparts[1] + matchedURLparts[2] : matchedURLparts[1];
}
else {
newURL = url;
}
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"
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);