Add new Param URL in the middle using javascript - 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);

Related

Javascript - Remove some part of URL and Add Query after

How can I remove some part of an url and add some query before returning it?
Example:
locahost:8080/product/orders/1.
I want to remove the orders/1 and add /?query="sample".
Use replace function:
location.replace("locahost:8080/product/?query='sample'")
You can get the url by simply doing window.location.href. You can then edit it by copying it to some new var newURL = window.location.href;
newUrl = newUrl.replace('/orders/1', '/?query=\"sample\"');
window.location.href = newUrl; // execute this to pass on the parameters to the current page.
Suppose you have url like this in variable1, let say like this
var variable1 = 'http://locahost:8080/product/orders/1'; //here you can get the actual browser url using `window.location.href`and assign it to `variable1`
just use replace function:
var final_text = variable1.replace('/orders/1','?query=sample');
you will get the following output, you do console.log(final_text);
http://locahost:8080/product?query=sample
You can try something like
var url = window.location.href;
var query = "somestring" ;
window.location.replace(url + "&" + somestring);
removing the / pieces:
var newloc = url.substring(0, url.search("/")) + query;
window.location.replace(newloc);

Replace a part of the URL with dropdown value - onchange

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")
)

How can I remove part of a url after a specific keyword?

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;
}

How to get url without page

I want to get url without page. Please see it below.
current url
http://localhost/FolderPath/Page.html
want to get
http://localhost/FolderPath/
How can I do this? Thanks.
var oldPath = 'http://localhost/FolderPath/Page.html';
var newPath = oldPath.split('/').slice(0, -1).join('/') + '/';
"http://localhost/FolderPath/Page.html".replace(/[^\/]*$/, '');
var url = "http://localhost/FolderPath/Page.html";
url = url.substr(0, url.lastIndexOf('/') + 1);
Regex anyone?
var url = "http://localhost/FolderPath/Page.html";
url.match(/(.+)(\/(.+)?)$/)[1] + "/";
//returns "http://localhost/FolderPath/"
var url = "http://localhost/FolderPath/";
url.match(/(.+)(\/(.+)?)$/)[1] + "/";
//returns "http://localhost/FolderPath/"

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.

Categories