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
Related
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>
I have an email in the following format:
joe+12312313#aDomain.com
First, I need to make sure the email's domain equals to aDomain.com
Next, I need to extract everything before the + sign
It would be nice if I can get a the following object:
var objParts = {
localPart: null,
domain: null,
};
console.log(objParts.localPart) // joe
console.log(objParts.domain) // aDomain.com
I know we have to use Regex. I am new to JS.
var email = "joe+12312313#aDomain.com";
var objParts = CreateEmailParts(email);
console.log(objParts.localPart);
console.log(objParts.domain);
function CreateEmailParts(email)
{
if(email)
{
var objParts = {
domain: email.split('#')[1], // caution: hoping to have the domain follow # always
localPart: email.split('+')[0], // caution: hoping to have the ema follow # always
};
return objParts;
}
}
https://jsfiddle.net/pdkvx82d/
It doesn't seem like you have to validate the generic email format here.
You can just split on the main points, # and +, and extract the data:
const email = 'joe+12312313#aDomain.com'
const domain = email.split('#').pop() // split on '#' and get the last item
const local = email.split('+').shift() // split on '+' and get the first item
console.log(domain);
console.log(local);
Use simple split:
var str = "joe+12312313#aDomain.com";
var parts = str.split("#");
var objParts = {
localPart: parts[0].split('+')[0],
domain: parts[1],
};
console.log(objParts);
Am trying to get the url's printed in a column and am getting this error:
"Incorrect range height,was 1 but should be 132 (line 37, file "Code")"
and when am getting the url in debugger, am getting it in this form:
"http\://myrul.com\:8080/abcde/" and i have more than 130+ urls which am getting from API. now my second concern is i wanna somehow split and get the url in this form:
"http://myrul.com:8080/abcde/"
(remove all the backslash's from all the 130 urls)
hope u guys can help
Thanks
here is the function that i have written:
`
function fetchFromApi() {
var url = '<<my api from where am fetching the data>>';
var urlResponse = UrlFetchApp.fetch(url);
var urlResult = JSON.parse(urlResponse);
var key = Object.keys(urlResult);
var tempArr = [];
for (var x in urlResult) {
var value = urlResult[x];
tempArr.push(value)
}
inputSheet.getRange(2,6,tempArr.length,1).setValues([tempArr]);
Logger.log(tempArr);
}
`
For the second part please use the following regex
value.replace(/\\/g, '');
Please insert it inside your loop.
Please see how it works here
var url = window.location.href.toString();
the above line gives me the url of my current page correctly and my url is:
http://localhost/xyzCart/products.php?cat_id=35
However, using javascript how can i get only a portion of the url i.e. from the above url i just want
products.php?cat_id=35
How to accomplish this plz help.I have looked at similar questions in this forum but none were any help for me..
You can sliply use this:
var url = window.location.href.toString();
var newString = url.substr(url.lastIndexOf(".") + 1));
This will result in: php?cat_id=35
Good luck /Zorken17
You can use the location of the final /:
var page = url.substr(url.substr(0, (url + "?").indexOf("?")).lastIndexOf("/") + 1);
(This allows for / in a query string)
You can get your desired result by using javascript split() method.check this link for further detail
https://jsfiddle.net/x06ywtvo/
var urls = [
"http://localhost/xyzCart/products.php?cat_id=35",
"http://localhost/xyzCart/products.php",
"http://www.google.com/xyzCart/products.php?cat_id=37"
];
var target = $('#target');
for(var i=0;i<urls.length;i++){
var index = urls[i].indexOf("xyzCart");
var sub = urls[i].substring(index, urls[i].length);
target.append("<div>" + sub + "</div>");
}
Try the folowing javacript code to get the part you need. It splits up your url by the "/"s and takes the fourth part. This is superior to substr solutions in terms of descriptive clarity.
url.split("/")[4]
Or if url can contain more "/" path parts, then simply take the last split part.
var parts = url.split("/");
console.log( parts[parts.length-1] );
You will get all necessary values in window.location object.
Kindly check on following CodePen Link for proper output.
I have added parameter test=1
Link: http://codepen.io/rajesh_dixit/pen/EVebJe?test=1
Code
(function() {
var url = window.location.pathname.split('/');
var index = 1;
document.write("URL: ");
document.write(window.location.href);
document.write("<br/> Full Path: ");
document.write(window.location.pathname);
document.write("<br/> Last Value:")
// For cases where '/' comes at the end
if(!url[url.length - index])
index++;
document.write(url[url.length-index])
document.write("<br/> Query Parameter: ");
document.write(window.location.search.substring(1));
})()
I am working with the FatSecret REST API
Im using the OAuthSimple javascript library to generate the signed url.
Here's the code I have -
params['oauth_timestamp'] = Math.floor(new Date().getTime()/1000);
params['oauth_nonce'] = '1234';
params['oauth_version'] = '1.0';
var paramStr = '';
for(var key in params){
paramStr += key+"="+params[key]+"&";
}
paramStr = paramStr.substring(0,paramStr.length-1);
var oauth = OAuthSimple();
oauth.setAction('GET');
var o = oauth.sign(
{
path:this.requestURL,
parameters: paramStr,
signatures:{
api_key:this.apiKey,
shared_secret:this.sharedSecret,
access_token: this.accessToken,
access_secret: this.accessSecret
}
});
console.log(o.signed_url);
return o.signed_url;
params is an associative array containing all the non oauth related parameters for this call.
When I use this signed url I get an "invalid/used nonce"
The OAuth Testing Tool uses the same OAuthSimple library and if I put in all the same parameters (including the timestamp) it generates exactly the same url.
The only difference is that the url generated by the testing tool works and gives me the full response from the server. The url generated by my code does't.
I tried various nonce values including sending a MD5 of the timestamp but I get the same error. The reason I'm using 1234 right now is that the testing tool uses 1234 by default and that seems to work.
Any help is appreciated. Thanks in advance.
Updating #Saravanan's answer with something that works on current browsers:
function genNonce() {
const charset = '0123456789ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvwxyz-._~'
const result = [];
window.crypto.getRandomValues(new Uint8Array(32)).forEach(c =>
result.push(charset[c % charset.length]));
return result.join('');
}
console.info(genNonce());
The nonce value as per twitter documentation:
The value for this request was generated by base64 encoding 32 bytes of random data, and stripping out all non-word characters, but any
approach which produces a relatively random alphanumeric string should
be OK here.
Based on the above notes, I use the following javascript code to generate nonce value each time I send a request:
var nonceLen = 32;
return crypto.randomBytes(Math.ceil(nonceLen * 3 / 4))
.toString('base64') // convert to base64 format
.slice(0, nonceLen) // return required number of characters
.replace(/\+/g, '0') // replace '+' with '0'
.replace(/\//g, '0'); // replace '/' with '0'
Try this if it works!
Try this
This works every time
var nonce = Math.random().toString(36).replace(/[^a-z]/, '').substr(2);