Access params in URL in JS (React) - javascript

I have this URL : http://localhost:3000/#access_token=90kzif5gr8plhtl9286sc1z1qbgoj3&scope=moderation%3Aread&token_type=bearer
and I want to get from this only the access_token value 90kzif5gr8plhtl9286sc1z1qbgoj3
How can I do it in Javascript please ?

Here is the solution:
const url = "http://localhost:3000/#access_token=90kzif5gr8plhtl9286sc1z1qbgoj3&scope=moderation%3Aread&token_type=bearer";
const hash = url.substring(url.indexOf('#') + 1);
let result = hash.split('&')
result = result[0].split('=')
console.log(result[1]); // "90kzif5gr8plhtl9286sc1z1qbgoj3"
Happy coding :)

As you can see in this the simplest way is :
var url_string = "http://localhost:3000/#access_token=90kzif5gr8plhtl9286sc1z1qbgoj3&scope=moderation%3Aread&token_type=bearer";
var url = new URL(url_string);
var c = url.searchParams.get("access_token");

You can try this by splitting the URL string into three strings and using the access token directly then
var url=http://localhost:3000/#access_token=90kzif5gr8plhtl9286sc1z1qbgoj3&scope=moderation%3Aread&token_type=bearer
var firstHalf=url.split('#access_token=')[1];
var required_token=firstHalf.split("&scope")[0];
print the value of required_token.
Required result will be "90kzif5gr8plhtl9286sc1z1qbgoj3"

your text is the string contained in window.location.hash, and a string of that format can be easily turned into a properly decoded key/value store using the URLSearchParams constructor:
const token = new URLSearchParams(window.location.hash).get("access_token");

Related

javascript url params to take out center string from url

my current url is http://localhost:8080/test/?usrType=t#8059433831715886
var channel = location.href.replace(/\?.*?#|[\/:#%.\[\]]/g, '');
it gives an output as httplocalhost8080test8059433831715886
i want the output as httplocalhost80808059433831715886
Using URL() constructor
const url = new URL('http://localhost:8080/test/?usrType=t#8059433831715886')
console.log((url.origin + url.hash).replace(/[^\w]/g, ''))

Get string between / in URL

Let's say I have the following URL https://www.google.com/en-gb/test-page.
I'm trying to extract whatever is after the domain name, in this case en-gb, however, with my approach, it's currently spitting out the entire slug.
I.e.
var pathname = window.location.pathname.substr(1);
console.log(pathname);
Will log out:
en-gb/test-page
How can I get it so that it only log out en-gb?
Just split the url with the / delimiter
const url = 'https://www.google.com/en-gb/test-page';
console.log(url.split('/')[3]);
You can use URL.pathname
Code:
const url = new URL('https://www.google.com/en-gb/test-page');
const str = url.pathname.split('/')[1];
console.log(str);
Split on a slash:
var [pathname] = window.location.pathname.substr(1).split("/");

Get last two params of an URL - javascript

My URL looks like this
stackoverflow.com/questions/ask/format/return
I need to get only format/return from the above URL. I'm able to assign the complete URL to a variable. Currently i'm doing it on split
url.split("/")[4]
url.split("/")[5]
And this is not Generic. What is the better way to achieve this?
The shortest, cleanest way to do this is by using slice on the splitted URL:
url.split("/").slice(-2).join("/")
Just use the length to help you index from the end:
var res = url.split('/')
var last = res[res.length-1]
var pre_last = res[res.length-2]
A genetic solution,
Var URL = url.split("/"); //
Last = URL[URL.length-1]; // return
LastBefore = URL[URL.length-1]; //format
url = "stackoverflow.com/questions/ask/format/return"
URL = url.split("/");
console.log(URL[URL.length-1]) // return
console.log(URL[URL.length-2]) //format
Look for the last and penultimate values:
let spl = url.split("/");
alert(spl[spl.length-2]+' and '+spl[spl.length-1]);
I'd parse the url to a URL, then use match on the pathname. This way it will also work should you have any searchparams (?foo=bar) in your url
const s = "https://stackoverflow.com/questions/ask/format/return";
const uri = new URL(s);
const m = uri.pathname.match(/([^\/]*)\/([^\/]*)$/);
console.log(m);
Note that you'll get an array holding three entries - 0 being the path combined, 1 the first and 2 the last param.
You can use a simple regex /.*\/(.*\/.*)/) to extract exactly what you want.
str.match(/.*\/(.*\/.*)/).pop()
var str = "stackoverflow.com/questions/ask/format/return",
res = str.match(/.*\/(.*\/.*)/).pop();
console.log(res);
var parts = url.split("/");
lastTwo = [parts.pop(), parts.pop()].reverse().join("/");

Javascript how to remove parameter from URL sting by value?

How to remove parameters with value = 3 from URL string?
Example URL string:
https://www.example.com/test/index.html?param1=4&param2=3&param3=2&param4=1&param5=3
If you are targeting browsers that support URL and URLSearchParams you can loop over the URL's searchParams object, check each parameter's value, and delete() as necessary. Finally using URL's href property to get the final url.
var url = new URL(`https://www.example.com/test/index.html?param1=4&param2=3&param3=2&param4=1&param5=3`)
//need a clone of the searchParams
//otherwise looping while iterating over
//it will cause problems
var params = new URLSearchParams(url.searchParams.toString());
for(let param of params){
if(param[1]==3){
url.searchParams.delete(param[0]);
}
}
console.log(url.href)
There is a way to do this with a single regex, using some magic, but I believe that would require using lookbehinds, which most JavaScript regex engines mostly don't yet support. As an alternative, we can try splitting the query string, then just examining each component to see if the value be 3. If so, then we remove that query parameter.
var url = "https://www.example.com/test/index.html?param1=4&param2=3&param3=2&param4=1&param5=3";
var parts = url.split(/\?/);
var params = parts[1].replace(/^.*\?/, "").split(/&/);
var param_out = "";
params.forEach(function(x){
if (!/.*=3$/.test(x))
param_out += x;
});
url = parts[0] + (param_out !== "" ? "?" + param_out : "");
console.log(url);
You could use a regular expression replace. Split off the query string and then .replace &s (or the initial ^) up until =3s:
const str = 'https://www.example.com/test/index.html?param1=4&param2=3&param3=2&param4=1&param5=3';
const [base, qs] = str.split('?');
const replacedQs = qs.replace(/(^|&)[^=]+=3\b/g, '');
const output = base + (replacedQs ? '?' + replacedQs : '');
console.log(output);

extract part of URL from parent URL

For this url
"http://testsite/sites/TestSubSite/objstrat/CultureConnection/Pages/default.aspx"
Trying to extract everything after enterprise/sites.
I want "/TestSubSite/objstrat/CultureConnection/Pages/default.aspx"
I can get the filename like this:
var filename = parenturl.substring(parenturl.lastIndexOf("/") + );
But not sure how to extract from the middle..
Using lastIndexOf will fail for any URI reference with / in the fragment or query, as in http://example.com/foo/bar#/baz/boo.
Libraries like Google Closure's Uri module can make this easy.
new goog.Uri(parenturl).getPath()
If your library of choice doesn't have URI support, then http://www.ietf.org/rfc/rfc3986.txt appendix B suggests
var urlRegex = /^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;
var path = decodeURIComponent(urlRegex.exec(parenturl)[5]);
will get you the path part.
Once you've got the path, you can then strip off the /sites/ part by doing something like
var pathSuffix = path.replace(/^\/sites\//, '/');
I love Javascript with DOM element.
var link = document.createElement('a');
link.href = "http://testsite/sites/TestSubSite/objstrat/CultureConnection/Pages/default.aspx";
link.protocol;
link.hostname;
link.port;
link.pathname;
link.search;
link.hash;
link.host;
link.pathname.replace(/^\/sites/,"") // "/TestSubSite/objstrat/CultureConnection/Pages/default.aspx"
The easiest thing might be to use javascript's Split() function and rebuild the string from the resulting array (leaving out the first couple items)
var parenturl = "http://testsite/sites/TestSubSite/objstrat/CultureConnection/Pages/default.aspx";
var tokens = parenturl.split("/");
for(var i=0;i<tokens .length;i++)
{
console.log(tokens [i]);
}
Hows about:
var parenturl = "http://testsite/sites/TestSubSite/objstrat/CultureConnection/Pages/default.aspx";
var filename = parenturl.match(/\/sites(.*)$/)[1];
alert(filename);

Categories