Getting string value from url - javascript

var url = "http://www.example.com/activate_account.html#123,572ad7f557455";
var userid = url.substring(url.indexOf("#") + 1);
var pass = url.substring(url.indexOf(",") + 1);
console.log("User id: " + userid + "Password: " + pass);
I would like to get string from the URL as value but when I try javascript code like above the value has been given is not what I want. The output that I get from code above is like this:
userid : 123,572ad7f557455 pass : 572ad7f557455
The problem is the userid. How can I display only 123 before the comma?
userid : 123

Simple way is:
var url = "http://www.example.com/activate_account.html#123,572ad7f557455";
var urlData = url.substring(url.indexOf("#") + 1);
var userinfo = urlData.split(',');
console.log("User id: " + userinfo[0]);
console.log("Password: " + userinfo[1]);
It's work if your password in param don't have ,.
If you password have ,, use slice to make sure it work:
var url = "http://www.example.com/activate_account.html#123,572ad7f557455";
var urlData = url.substring(url.indexOf("#") + 1);
var userinfo = urlData.split(',');
var userId = userinfo[0];
var userinfo = urlData.split(',');
var userPassword = urlData.slice(userId.length + 1, urlData.length); // userId.length + 1 to remove comma
console.log("User id: " + userId);
console.log("Password: " + userPassword);

You could try to set end index for substring() method by url.indexOf(",") like this:
var userid = url.substring(url.indexOf("#") + 1, url.indexOf(","));
N.B. split() may help you if there is no , at password field.

try this:
var url = "http://www.example.com/activate_account.html#123,572ad7f557455";
var params = url.substring(url.indexOf("#") + 1).split[','];
var userid = params[0];
var pass = params[1];
console.log("User id: " + userid + "Password: " + pass);

This is not the right way to send params through URL, you need to change it like http://www.example.com/activate_account.html?paramName=123 then you can get your data by param name. And also sending user name and password like this is not good at all, you need to put that in authorization header which will be encoded by base 64 for security purposes.

Related

how to concatenate string with double quotes to generate JSON?

var skillTargetID = "1234";
var agentId = "2345";
var firstName = "Ganesh";
var lastName = "Putta";
var userName = "ganesh#gmail.com"
agentjson = {
"refURL": "/unifiedconfig/config/agent/" + skillTargetID + "," + "agentId" + ":" + agentId + "," + "firstName" + ":" + firstName + "," + "lastName" + ":" + lastName + "," + "userName" + ":" + userName
};
console.log(agentjson);
I got a string like below
"refURL":"/unifiedconfig/config/agent/5113","agentId":"1312","firstName":"John","lastName":"Elway","userName":"jelway"
i need to concatenate above string using javascript with dynamic values, i tried, but in the result double quotes are not appending for every word.
agentjson={"refURL":"/unifiedconfig/config/agent/"+skillTargetID+","+"agentId"+":"+agentId+","+"firstName"+":"+firstName+","+"lastName"+":"+lastName+","+"userName"+":"+userName};
this is result i got.
{"refURL": "/unifiedconfig/config/agent/1234,agentId:2345,firstName:Ganesh,lastName:Putta,userName:ganesh#gmail.com"}
how to cancatenate string to get the exact result like first one.
You need an object and then you need to stringify it
You can use template literals to embed variables in a string and the rest you can just write the variable name in the object
const createJSONString = (skillTargetID, agentId, firstName, lastName, userName) => {
const obj = {refURL : `/unifiedconfig/config/agent/${skillTargetID}`,
agentId, firstName, lastName, userName};
return JSON.stringify(obj);
}
var skillTargetID = "1234";
var agentId = "2345";
var firstName = "Ganesh";
var lastName = "Putta";
var userName = "ganesh#gmail.com"
console.log(createJSONString(skillTargetID, agentId, firstName, lastName, userName))

Return a selected part of string using IBM Gateway script

How do I extract certain parts of a string from a whole string?
My string looks like:
&username=user&password=pass&client_id=cid&client_secret=secret&grant_type=password
I want to extract the username and password values into 2 variables.
These values can appear in any order in the string.
It can be done this way:
let a = '&username=user&password=pass&client_id=cid&client_secret=secret&grant_type=password'.split('&')
let user, passwordData
for(let i=0; i<a.length; i++){
if (a[i].includes('username=')){
user= a[i].substr(9)
}
if (a[i].includes('password=')){
passwordData= a[i].substr(9)
}
}
console.log(user, passwordData) // logs values
Use RegEx to split your string and get value like below.
let str = '&username=user&password=pass&client_id=cid&client_secret=secret&grant_type=password';
function getResult() {
let arr = {};
let KeyValueResult = str.replace(/[&]+([^=&]+)=([^&]*)/gi, function(m, key, value) {
arr[key] = value;
});
return arr;
}
let username = getResult()["username"];
let password = getResult()["password"];
let client_id = getResult()["client_id"];
let client_secret = getResult()["client_secret"];
let grant_type = getResult()["grant_type"];
console.log('username: ' + username + ' password: ' + password + ' client_id: ' + client_id + ' client_secret: ' + client_secret + ' grant_type: ' + grant_type);
Function doesn't care about order. Just call with key it's give desire value.
Well, it actaully easier than that as DataPower ships the QueryString Module out-of-the-box...
const querystring = require ('querystring');
const qs = querystring.stringify('username=user&password=pass&client_id=cid&client_secret=secret&grant_type=password');
// returns {username: 'user' , password: 'pass', ... }
console.log('username: ' + qs.username + ' password: ' + qs.password);
Read the full documentation here: https://www.ibm.com/support/knowledgecenter/SS9H2Y_7.5.0/com.ibm.dp.doc/querystring_js.html

Ionic 3, encodeURI with firebase

I need to send a http request to firebase that has this shape
https://db.firebaseio.com/0.json?&orderBy="name"&startAt=query&endAt=query+"\uf8ff"&limitToLast=1&print=pretty&auth=auth_token
My problem is that when I call this request I've a 400 error in console because it replace %22 to question marks and other symbols for \uf8ff and I think firebase doesn't recognize that.
let name = '"name"';
let cod = '"\uf8ff"';
let url = ('https://db.firebaseio.com/0.json?&orderBy=' + encodeURIComponent(name) + '&startAt=' + encodeURIComponent(birraName) + '&endAt=' + encodeURIComponent(birraName) + '+' + encodeURIComponent(cod) + '&limitToLast=1&print=pretty&auth=' + encodeURIComponent(this.idToken));
let response = this.http.get(url).map(res => res.json());
return response;
And then in console
400 Bad Request
Do you have any thougths?
You're missing quotes in your target string to mark string values. If you're searching for nodes starting with Marco, it should be https://db.firebaseio.com/0.json?&orderBy="name"&startAt="Marco"&endAt="Marco\uf8ff"&limitToLast=1&print=pretty&auth=auth_token. Note the double quotes around "Marco" and "Marco\uf8ff".
To build these in your JavaScript:
var url = 'https://db.firebaseio.com/0.json';
url = url + '?orderBy="' + encodeURIComponent(name) + '"';
url = url + "&startAt="' + encodeURIComponent(birraName) + '"';
url = url + "&endAt="' + encodeURIComponent(birraName) + '\uf8ff"';
url = url + '&limitToLast=1&print=pretty';
url = url + '&auth="' + encodeURIComponent(this.idToken))+'"";
Template literals might also be useful to keep this readable:
let url = (`https://db.firebaseio.com/0.json?orderBy=${encodeURIComponent(name)}&startAt=${encodeURIComponent(birraName)}&endAt=${encodeURIComponent(birraName)}${encodeURIComponent(cod)}&limitToLast=1&print=pretty&auth=${encodeURIComponent(this.idToken))}`;

Azure Account Shared Access Signiture

I am trying to construct an Account level Shared Access Signiture so my client can access all containers in a storage account. I am following these docs Account SAS. It seems straight forward enough but I keep getting the following error message:
"Signature did not match. String to sign used was accountname\nrl\nb\nsc\n\n2016-10-09\n\n\n2015-04-05\n".
My parameters are identical so I suspect it has something to do with how I am hashing the String to Sign. Below is how I construct the token.
var crypto = require('crypto');
var accountName = 'accountname';
var accountKey = 'tH37FTlG3TUT86caMrt2y5kOzof8nFqqA6spzg6r7HPRojE1zDiLJD/xE4oLFDh4RNqAmymvlV7fm8W4SF8cJg==';
var signedPermissions = "sp=rl";
var signedServcies = "ss=b";
var signedResourceType = "srt=sc";
var signedExpiry = "se=2016-10-09";
var signedVersion = "sv=2015-04-05";
var stringToSign = accountName + "\n" + signedPermissions + "\n" + signedServcies + "\n" + signedResourceType + "\n" + signedExpiry + "\n" + signedVersion + "\n";
var hmacsha256 = crypto.createHmac('sha256', accountKey).update(stringToSign).digest('base64');
var token = signedPermissions + "&" + signedServcies + "&" + signedResourceType + "&" + signedExpiry + "&" + signedVersion + "&sig=" + hmacsha256;
I have tried using crypto-js as well but to no avail. The final URL used to access a blob in a container is...
"https://accountname.blob.core.windows.net/containername/blobName?srt=sc&se=2016-10-09&api-version=2015-04-05&sp=rl&ss=b&sv=2015-04-05&sig=IFD2wyfRAsHGU5IFg3RbwSJW6tRE0m0%2FxgAYvJ%2FmnEk%3D"
I have been trying for days and really would appreciate knowing what I'm doing wrong. Thanks.
Benzene, for stringToSign, the value should NOT has the parameter name?
var signedPermissions = "rl";
var signedServcies = "b";
var signedResourceType = "sc";
var signedExpiry = "2016-10-09";
var signedVersion = "2015-04-05";
Please try the following (code shamelessly taken from Azure Storage Node.js library):
var hmacsha256 = crypto.createHmac('sha256', new Buffer(accountKey, 'base64')).update(stringToSign, 'utf-8').digest('base64');

Appending variables to a string in javascript

I am using prototype in my application but I am not sure how to add this correctly. Basically I have the following function and I need to construct the href of an anchor from which I already have the reference to a series of appended values
MyJavascriptClass.prototype.init = function() {
this.ToDate = $(this.Prefix + 'ToDate');
this.FromDate = $(this.Prefix + 'FromDate');
}
so in the following function I need to add those as parameters in the url attribute
MyJavascriptClass.prototype.btnClicked = function(evt) {
this.lnkShowLink.setAttribute('href', 'MyWebpage.aspx?StartDate=7/18/2012&EndDate=1/19/2012');
}
How can i do something like 'MyWebPage.aspx?StartDate=this.ToDate&EndDate=this.FromDate' ? Any help would be appreciated.
If you are using jquery, and $(this.Prefix + 'ToDate') and $(this.Prefix + 'FromDate') represent fields that contain values, then you can do this:
MyJavascriptClass.prototype.btnClicked = function(evt) {
this.lnkShowLink.setAttribute('href', 'MyWebpage.aspx?StartDate=' + this.ToDate.val() + '&EndDate=' + this.FromDate.val() + '');
}
It is difficult to tell from your code what they represent, and why you have them wrapped in $(..).
If ToDate and FromDate contain the two date values, then this should work...
'MyWebPage.aspx?StartDate=' + this.ToDate + '&EndDate=' + this.FromDate
If you don't know every properties:
var properties = [];
for(var i in this)
if(this.hasOwnProperty(i))
properties.push(i+'='+this[i]);
var url = 'MyWebPage.aspx?'+properties.join('&');
var string = "My name is: ",
name = "Bob",
punctuation = ".",
greeting = string + name + punctuation;
Or
var User = { name : "Bob", age : 32, sign : "Leo" },
welcome = "Hi, I'm " + User.name + ", and I'm " + User.age + " years old, I'm a " + User.sign + ", and I enjoy long walks on the beach.";

Categories