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))
Related
How to get regex with replace method? In my case I've got string which uses char / between.
input:
var string = "cn/" + companyName + "/st/" + state + "/ic/" + incCi + "/pr/" + priority + "/es/" + emplSystem + "/mc/" + mainCategory + "/sc/" + subCategory + "/ty/" + type;
output:
"cn/Nemesis Group/st/2/ic/null/pr/1 - High/es/null/mc/Add/Button/sc/Core/Label/ty/str"
variable mainCategory and subCategory returns string 'Add/Button' and 'Core/Label'
How to replace 'Add/Button' to 'Add%2FButton' and 'Core/Label' to 'Core%2FLabel' without changing any other char?
string.replace("\/", "%2F")
will change all char / to %2F
You can use encodeURIComponent() and decodeURIComponent() to transform this String
Example:
const companyName = "Company",
state = "State",
incCi = "IncCi",
priority = "Priority",
emplSystem = "EmplSystem",
mainCategory = 'Add/Button',
subCategory = 'Core/Label',
type = "Type";
var string = "cn/" + companyName + "/st/" + state + "/ic/" + incCi + "/pr/" + priority + "/es/" + emplSystem +
"/mc/" + encodeURIComponent(mainCategory) +
"/sc/" + encodeURIComponent(subCategory) + "/ty/" + type;
console.log(string)
It sounds to me like you are looking to encode the url. You can use encodeURI in JS to encode a url.
let encodedURL = encodeURI(url);
You can read more about it here.
If you want to encode the string altogether without ignoring any domain related parts, you can us encodeURIComponent()
let encodedURL = encodeURIComponent(url);
You can read more about their differences here.
EDIT:
If you are not encoding a url and you just want to repalce / with %2F only in mainCategory and subCategory then you need to run the regex on the string itself before joining them.
var string = "cn/" + companyName +
"/st/" + state +
"/ic/" + incCi +
"/pr/" + priority +
"/es/" + emplSystem +
"/mc/" + mainCategory.replace("\/", "%2F") +
"/sc/" + subCategory.replace("\/", "%2F") +
"/ty/" + type;
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
Need to dynamically select JSON key from the JSON Object itself.
var text =
'{"employees":[' + '{"firstName":"lastName", "lastName":"Doe" }]}';
var obj = JSON.parse(text);
var firstName = obj.employees[0].firstName;
var lName = obj.employees[0].firstName;
document.getElementById("demo").innerHTML =
firstName + " " + obj.employees[0].lName;
<div id="demo"></div>
Output Obtained: "lastName undefined".
Desired Output: "lastName Doe"
You need to change the code like follows
var text = '{"employees":[' +
'{"firstName":"lastName","lastName":"Doe" }]}';
obj = JSON.parse(text);
var firstName = obj.employees[0].firstName;
var lName = obj.employees[0].firstName;
document.getElementById("demo").innerHTML =
firstName + " " + obj.employees[0][lName];
Here is the working code:http://jsfiddle.net/NJMyD/5349/
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.
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.";