So I want to get the Object which is essentialy a string. The issue is I cant transfer it into the string format since the resulting string is just anything but the thing I want. Bringing the object into a json doesnt bring a proper string either so my only way of achieving that is the concat method.
I have a Popup-Love which returns the string as follows foo, foo1 ,foo2 while I need it as
'foo1','foo2',...,'foo999' .
My method manages to do that for the first element while all the other elements remove the apostrophe resulting in something like 'foo,foo1,foo2'. How do i fix that?
var i = 0;
if(i == 0){
var t ="'";
var t = t.concat(apex.item("P29_STANDORT").getValue());
var t = t.concat("'");
apex.item("P29_TEST").setValue(t);
i = i +1;
} else {
var t = t.concat("'");
var t = t.concat(apex.item("P29_STANDORT").getValue());
var t = t.concat("'");
apex.item("P29_TEST").setValue(t);
}
You can "overwrite" the native toString() function of the Object and replace it with a function that does what you want. Something like below
function MyObj(){
this.creationTime = new Date().toLocaleString();
}
MyObj.prototype.toString = function something(){
return 'I was created on ' + this.creationTime;
}
var myObj = new MyObj();
console.log('String version of my custom object: ' + myObj);
Related
How do I pass the whole dictionary inside the template literal?
Here is my code:
var pvtInPlan = treatmentPlan.pavementIDs;
var pcrAfterPlan = treatmentPlan.pavementCondition;
var yearlyPlan = {};
pvtInPlan.forEach((key, i) => yearlyPlan[key] = pcrAfterPlan[i]); // I want to pass this yearlyPlan
var arcadeExpression = `
var plan = ${yearlyPlan};
var pvtID = 100;
return plan[pvtID]`; // I want to be able to return such statement.
Whenever I use 'var plan = ${yearlyPlan};' line, it throws me error. It works when I use 'var plan = ${yearlyPlan[100]};' directly. But I need to pass index to this dictionary from inside of template literal.
I would be glad if someone could help me with this.
Thanks!
You can just do a simple JSON.stringify if u want to dump the entire content, for example:
const yearlyPlan = JSON.stringify({ key1: 'content', key2: 'content2' })
const arcadeExpression = `
var plan = ${yearlyPlan};
var pvtID = 100;
return plan[pvtID]`; // I want to be able to return such statement.
console.log(arcadeExpression)
>>>
"var plan = {"key1":"content","key2":"content2"};
var pvtID = 100;
return plan[pvtID]"
If you want a more customized version, then u would need to access each key-value pair to format the message.
Grab the substring:
var hash = document.location.hash;
// create an object to act like a dictionary to store each value indexed by its key
var partDic = {};
// remove the leading "#" and split into parts
var parts = hash.substring(1).split('&');
// If you just want the first value, whatever it is, use this.
// But be aware it's a URL so can be set to anything in any order, so this makes little sense
// var string = parts[0].split('=')[1];
// build the dictionary from each part
$.each(parts, function(i, v) {
// do the "=" split now
var arr = v.split("=");
// decode to turn "%5B" back into "[" etc
var key = decodeURIComponent(arr[0]);
var value = decodeURIComponent(arr[1]);
// store in our "dictionary" object
partDic[key] = value;
});
// Set a delay to wait for content to fully load
setTimeout( function() {
var ag = partDic["comboFilters[Agencies]"].substring(1);
$('.Agency .dropdown-toggle').html(ag).append(' <span class="caret"></span>');
var cl = partDic["comboFilters[Clients]"].substring(1);
$('.Client .dropdown-toggle').html(cl).append(' <span class="caret"></span>');
var yr = partDic["comboFilters[Years]"].substring(1).slice(1);
$('.Year .dropdown-toggle').html(yr).append(' <span class="caret"></span>');
}, 1000);
But if there is not a substring, I am getting:
Uncaught TypeError: Cannot read property 'substring' of undefined
Suggested answer in another question
var cl = (partDic["comboFilters[Clients]"] && partDic["comboFilters[Clients]"].length>0)?partDic["comboFilters[Clients]"].substring(1):'';
But I still get the same error
You can be defensive and check if a key exists before using it:
if("comboFilters[Agencies]" in partDic) {
var ag = partDic["comboFilters[Agencies]"].substring(1);
$('.Agency .dropdown-toggle').html(ag).append(' <span class="caret"></span>');
}
or just safeguard it with an empty string:
var ag = (partDic["comboFilters[Agencies]"] || "").substring(1);
Maybe try with things like:
var parts = (hash && hash.substring(1).split('&')) || [];
You can try to check it's type:
var cl = (typeof partDic["comboFilters[Clients]"] === 'string')?partDic["comboFilters[Clients]"].substring(1):'';
Note, that you should add this check for all your variables: ag, cl, yr
You can check one condition before using substring method..
if((!hash) || (!hash.substring(1)){
return false;
}
I have a json like this:
var x = {"foo:bar":"xyz"};
I can get xyz by call x["foo:bar"] but is there anyway to get xzy by calling just bar and remove the foo prefix? something like x["bar"]? The json is converted from xml with namespace like that, I can't change it. Thanks
You can iterate over the property names and remove the prefix:
function removePrefix(x){
var temp = {};
for(var key in x){
temp[key.substr(key.indexOf(':')+1)] = x[key];
}
return temp;
}
var x = {"foo:bar":"xyz"};
x = removePrefix(x);
console.log( x['bar'] ); // xzy
console.log( x.bar ); // xyz
You would create a JSON string which would look like this:
var x = {"foo":"xyz"};
your current key: "foo:bar" does not have any special meaning in JSON, it's part of the key.
I'm working on a simple browser mud-client, and i need to provide some basic functions to string processing. So, when some user casts a mass spell, it should be collapsed into a one string, i.e. CAST: User1 -> [target1, target2]. I wrote the code:
function CastGroup(caster, cast, targets, text) {
this.cast = cast || '';
this.targets = targets || [];
this.caster = caster || '';
this.text = text || '';
}
CastGroup.prototype = new String;
CastGroup.prototype.render = function(){
var targets = this.targets ? '[' + this.targets.join(', ') + ']' : '';
var text = '<b>CAST</b>: ' + this.caster + ' ' + this.cast + ' -> ' + targets + '\n';
this.text = text;
return new CastGroup(this.caster, this.cast, this.targets, this.text);
};
CastGroup.prototype.valueOf = function(){
return this.text;
};
CastGroup.prototype.toString = function(){
return this.render();
};
var c = new CastGroup('name', 'supercast', ['1', '2']);
console.log(typeof c); // object
var s = c.replace('name', 'nomnom');
console.log(typeof s); // string
Any string function, i.e. String.replace() replaces the original object. How can i avoid it?
EDIT1
I have a post-process highlighting "engine", that calls user's callbacks. User should think, that bundle has only strings. bundle is an array with raw text, plain text, and colorized text. User defines callbacks in user-space, that should do all the highlighting work.
function process_highlights(bundle){
if (!bundle || !bundle.length){
return bundle;
}
var highlight_result = bundle;
for (var i=0; i<HIGHLIGHTS.length; i++){
highlight_result = HIGHLIGHTS[i](highlight_result);
}
return highlight_result;
}
So, text process chain looks like: original_bundle -> subst_processor -> trigger_processor -> highlight_processor -> output_window. All of these processors takes and return a bundle, that should contain strings. I cannot change the design now.
If I understand your question correctly, you need to remove this: CastGroup.prototype = new String;
and do this: CastGroup.prototype = String.prototype;
This will give you the String methods without returning a new String object. To learn more about this (and about advanced Javascript in general), check out these slides.
Update:
I think I understand your question a little better now. The replace string method returns a new string, which is why it's overwriting your object.
You don't need to inherit from the String object at all. String methods won't even work on an object (so delete CastGroup.prototype = new String). What you want to do is just modify the object's values directly.
If you need to modify the 'text' value of your CastGroup, then declare another method:
CastGroup.prototype.modifyText = function (findValue, replaceValue) {
var text = this.text;
this.text = text.replace(findValue, replaceValue);
return this;
};
This worked for me.
CastGroup.prototype.replace = function() {
this.text = this.text.replace.apply(this.text, arguments);
return this;
};
Overwrite the prototype in your object, update the field that needs updating, then return the object.
I know about GET variables and javascript there are many questions, but I do not understand or get them to work.
I have a html formular, and I need to populate a field with the value of the get variable. The url has 2 variables, here an example:
?pid=form.html&id=9869118
This page is a html only, so I cannot use php, but I want to (firstly) alert, the value of id.
I have tried so many different versions of solutions here and from google.
(For example:
http://www.onlineaspect.com/2009/06/10/reading-get-variables-with-javascript/
Please help me to understand how its done correctly and save! Please note, I have no jquery either.
Here is what I have tried so far. This is inside the <script> tags inside my form.html
var GETDATA = new Array();
var sGet = window.location.search;
if (sGet)
{
sGet = sGet.substr(1);
var sNVPairs = sGet.split("&");
for (var i = 0; i < sNVPairs.length; i++)
{
var sNV = sNVPairs[i].split("=");
var sName = sNV[0];
var sValue = sNV[1];
GETDATA[sName] = sValue;
}
}
if (GETDATA["id"] != undefined) {
document.forms.otayhteytta.id.value = GETDATA["id"];
}
Take a look at this excellent javascript url manipulation library:
http://code.google.com/p/jsuri/
You can do stuff like this:
Getting query param values by name
Returns the first query param value for the key
new Uri('?cat=1&cat=2&cat=3').getQueryParamValue('cat') // 1
Returns all query param values the key
new Uri('?cat=1&cat=2&cat=3').getQueryParamValues('cat') // [1, 2, 3]
You can use a pure JavaScript function for that like so:
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
And then you can alert the value of 'id' like so:
alert(getParameterByName('id'));
You can check if the parameter exists using a simple 'if' condition:
var id = getParameterByName('id');
if (id != "") {
alert(id);
}
Source: How can I get query string values in JavaScript?
A simple way to get the GET parameters without using a library:
var parameters = []
var parts = location.search.substr(1).split('&')
for(var part in parts) {
var splitted = parts[part].split('=')
parameters[splitted[0]] = splitted[1]
}
Now parameters is an array with the parameter name in the key and the value as the value.
This is a simple solution and may not work for all scenario's.