Way to get full param value from an URL - javascript

I am try to get the data from the param in the URL
http://localhost:8080?test=1&redirectURL=http://localhost:8082/#/abc?param=1
I did
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
const redirectURL = urlParams.get('redirectURL'); // result: http://localhost:8082
but currently, the URL contain the hash code inside URL so the value return just http://localhost:8082
Is there any way to get full url http://localhost:8082/#/abc?param=1 by getting the param redirectURL
Thank you very much

I hope the following is useful for you.
var url_string = window.location.href;
var url = new URL(url_string);
var paramsTest = url.searchParams.get("test");
var paramsRedirectURL = url.searchParams.get("redirectURL");
console.log(paramsRedirectURL)
console.log(paramsTest)
Example here: https://codepen.io/yasgo/pen/dypWKoM

Maybe this can work for you
var afterHash = window.location.hash;
var beforeHash = window.location.href;
var fullURL = beforeHash ;
if(afterHash != '') // if there is something after hash and hash is exists in url then add the afterHash value in full url
{
var fullURL = beforeHash +"#"+ afterHash ;
}
console.log(fullURL);

I think the biggest issue here is that your redirectURL is not encoded. It should be encoded before it ends up in the URL, because otherwise the params and hashes from the nested URL are going to spill into the parent URL.
I obviously don't know if it would make sense for your project, but I think I would use domurl.
Maybe you should just use encodeURIComponent and possibly decodeURIComponent later, but I wanted to point out that domurl handles encoding and decoding automatically. Just as an example:
var url = new Url("http://localhost:8080?test=1");
url.query.redirectURL = 'http://localhost:8082/#/abc?param=1';
console.log( url.toString() );
// http://localhost:8080/?test=1&redirectURL=http%3A%2F%2Flocalhost%3A8082%2F%23%2Fabc%3Fparam%3D1
So again, what the encoded URL does is it prevents params from spilling from the nested URL to the parent URL and enables you to read redirectURL as a single string that you can then parse again to see/edit whatever params it has. The other important point is that I'm removing the hashtag with replace('/#/','/') in order to read the params from redirectURL:
Here's a slimmer jsfiddle where I'm just extracting the param and leave everything else out.
You'll definitely want to check dev tools consode log instead of the one stackoverflow offers, to make any sense of the objects.
console.log('');
// I'm encoding the redirectURL here, but in the real world it should be encoded before it's added as a parameter.
var url = new Url("http://localhost:8080?test=1&redirectURL="+ encodeURIComponent("http://localhost:8082/#/abc?param=1"));
console.log('url', url);
// So now that I've separated `url.query.redirectURL`, I can read that URL and its params separately...
var redirectUrl = new Url( url.query.redirectURL.replace('/#/', '/') ); // The hashtag is removed
console.log('redirectUrl:', redirectUrl );
console.log('redirectUrl - (param):', redirectUrl.query.param );
console.log('redirectUrl - path:', redirectUrl.path );
// If you need to use redirectURL without modifications you can just take the url param as is:
console.log( 'redirectUrl - no edits:', url.query.redirectURL );
// If you need to edit the params, you could do that and put just back the hashtag
redirectUrl.query.param = 'changed the param';
redirectUrl.path = '/#' + redirectUrl.path
console.log('redirectUrl - edited:', redirectUrl.toString() );
<script src="https://cdn.jsdelivr.net/npm/domurl#2.3.4/url.min.js"></script>

Related

Redirect to another website (New ur has parameter) and add on current parameters (how to remove ? and add just &)

I'm passing URL parameters from the current link to another link but the new parameters are added as "&?firstName=test&lastName=testing" and should be just "&firstName=test&lastName=testing"
<script>
$('#redirectButton').click(function() {
const url = window.location.href;
const params = url.split('/');
const parameter = params[params.length-1];
const page2 = "www.newwebsite.com/page?existingParam=true" +parameter;
window.location.href = page2
});
</script>
If your URL is something like www.mywebsite.com/blah/blahblah/test?a=1&b=2, then the last item of the split list would be test?a=1&b=2. Blindly adding this to something like www.myotherwebsite.com/blah/test?existing=true would give www.myotherwebsite.com/blah/test?existing=truetest?a=1&b=2. However, you only want a=1&b=2 to be added (and of course, an & before all that). Thus, we can split by ? and add & plus the last part.
let url = 'www.mywebsite.com/blah/blahblah/test?a=1&b=2';
let redirectURL = 'www.myotherwebsite.com/blah/test?existing=true';
let splitL = url.split('/');
console.log('Redirecting to...');
console.log(redirectURL + '&' + splitL[splitL.length - 1].split('?')[1]);
This is assuming that your URL is not like www.someotherwebsite.com/test?a=1&text=Hello,%20how%20are%20you%20doing? with a question mark in the parameters. If it is, then you should use indexOf to find the index of the first question mark in splitL[splitL.length - 1], and use a slice from that index (plus 1) instead.

remove parameter from url via regex

I have a function for removing the parameter from url.
this is my function :
function removeParameter(key) {
let parameters = document.location.search;
const regParameter = new RegExp('[?|&]' + key + "=([a-zA-Z0-9_-]+)");
if (regParameter.test(parameters)){
parameters = parameters.replace(regParameter , '')
}
window.history.pushState({}, '', parameters)}
when I call this function for the url like this
http://example.com/products?color=4&brand=apple
first call function for removing the brand is correct result
removeParameter('brand')
but another call this function for removing the color doesn't work correctly.
actually when i want to removing the first parameter(key come's after ? mark) this function doesn't work...
The third argument to pushState() is the entire URL. Your function is sending only the location.search i.e. query parameter part of the URL. So you'll need to do
window.history.pushState({}, '', location.pathname + parameters)}
on your function's last line. Also, your code is currently not handling the edge cases i.e. if you remove first parameter, it removes the ? and not the trailing &. So you end up with http://example.com/products&brand=apple which isn't a valid URL. And finally, I simplified your expression a bit.
const reg = new RegExp('[?&](' + key + '=[\\w-]+&?)');
let matches = reg.exec(parameters);
if (matches){
parameters = parameters.replace(matches[1], '');
}
This still doesn't handle more complex cases (params without values, hash etc). There are a couple of other options:
Dump the regex and go with a split('&') based solution. More code, but a lot more readable and less error-prone.
If you don't need IE support, use URLSearchParams. Then your entire function can be reduced to this:
var params = new URLSearchParams(location.search);
params.delete(key);
window.history.pushState({}, '', location.pathname + "?" + params.toString());
Correct me if I'm wrong,
I made a working snippet out of your code, and it seems to work correctly.
If you run the snippet on a fresh new tab, it will add 2 urls in the tab history.
I also modified your regex to make it easier.
function removeParameter(key) {
var parameters = url; // document.location.search; // TAKIT: modified for test
const regParameter = new RegExp('[?|&]' + key + "=([^&]+)"); // TAKIT: Simplified regex
if (regParameter.test(parameters)) {
parameters = parameters.replace(regParameter, '')
}
window.history.pushState({}, 'Test 1', parameters);
return parameters; // TAKIT: Added
}
// Output
var url = "https://stacksnippets.net/js?color=4&brand=apple";
console.log(url);
url = removeParameter("brand");
console.log(url);
url = removeParameter("color");
console.log(url);
Hope it helps.
This function can be used, i modified #Takit Isy answer
function removeParameter(key) {
var parameters = url; // document.location.search; // TAKIT: modified for test
const regParameter = new RegExp(key + "=([a-zA-Z0-9_-]+[&]{0,1})");
if (regParameter.test(parameters)) {
parameters = parameters.replace(regParameter, '')
if(parameters.substring(parameters.length-1)=='?' || parameters.substring(parameters.length-1)=='&'){
parameters = parameters.slice(0, -1);
}
}
return parameters; // TAKIT: Added
}

Trying to redirect to the same page but with querystring value

I want to redirect to the same page, but add some querystring values.
If there is already a querystring value, I want to strip it out and add a new one.
My code isn't working currently, not sure why:
var url = window.location.href;
if(url.indexOf("?") > 0) {
url = url.substring(0, url.indexOf("?"));
} else {
url += "?joined=true";
}
window.location.replace(url);
The problem is that you're not adding the new query string when you strip off the old one, only in the else clause when there's no old query string. Take that addition out of the else, so you do it all the time.
var url = window.location.href;
if(url.indexOf("?") > 0) {
url = url.substring(0, url.indexOf("?"));
}
url += "?joined=true";
window.location.replace(url);
It would be better to use the already-available URL API.
var url = new URL(window.location.href);
url.searchParams.set('joined', true);
window.location.replace(url.toString());
You can check the following links to learn more about it:
https://developer.mozilla.org/en/docs/Web/API/URL
https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams

pulling text from url and putting text back in url with javascript

I have tried googling this but can't find what I'm looking for. I have a url that has a number in it. I want to be able to take the number that is there and depending on what number is there then interject a name back into the url. For example:
Let's say the url is: www.example.com/video15637
Can I take that number and then do something like:
var nameVariable;
if(video15637){
nameVariable = video15637;
}
if(video26597){
nameVariable = video26597;
}
if(video18737){
nameVariable = video18737;
}
then, somehow interject the namevariable back into the url that is displayed?
You can try with:
var a = document.createElement('a');
a.href = 'http://www.example.com/video15637';
var nameVariable = a.pathname.substr(1); // video15637
You can simple use .split() or combination of .substr() and .lastIndexOf()
var url = 'www.example.com/video15637';
var video = url.split('/')[1];
alert(video)
OR
var url2 = 'http://www.example.com/video15637';
var video2 = url.substr(url.lastIndexOf('/') + 1);
alert(video2)
Combined DEMO

Pulling specific variable from URL with javascript

How do I get the access_token variable in my URL using javascript .match()?
http://www.facebook.com/connect/login_success.html#access_token=pYBACn8NQeCAVWgiaFG4ZD&expires_in=0
Thanks a lot for your help!
var url = 'http://www.facebook.com/connect/login_success.html#access_token=pYBACn8NQeCAVWgiaFG4ZD&expires_in=0';
var token = url.split("#")[1].match(/access_token=([^&]+)/)[1];
The same as Parth's solution, but without split and a tiny bit more strict:
var url = 'http://www.facebook.com/connect/login_success.html#access_token=pYBACn8NQeCAVWgiaFG4ZD&expires_in=0';
var token = url.match(/(?:#|#.+&)access_token=([^&]+)/)[1];
Same as Eugene's but does not throw exception should the match fail
var url = 'http://www.facebook.com/connect/login_success.html#access_token=pYBACn8NQeCAVWgiaFG4ZD&expires_in=0';
var token = (url.match(/(?:#|#.+&)access_token=([^&]+)/) || ['', null])[1];
Returns null if the token is not present in the URL

Categories