So I have a javascript function that take a string as argument. That string can be a simple string OR a sugarcube variable format “$variables”. In this second case I would like to get the real value of the variables.
function getRealValueIfVariable(str) {
return magicFunction(str);
}
/* For example if I have $name set to "John" I would like the function to return */
getRealValueIfVariable("name");
==> "name"
getRealValueIfVariable("$name");
==> "John"
Using those objects, you have no need for such a function. If you want to access $name in JavaScript, then you’d just use State.variables.name instead. If the name of a variable is in another variable, then you can do this:
var variableName = "name";
var result = State.variables[variableName];
This also allows you to set variables from JavaScript:
// Make sure the first letter of the name is capitalized.
State.variables.name = State.variables.name.toUpperFirst();
If you need to work with a lot of variables and don’t want to type “State.variables” over and over, you can shorten that like this:
var sv = State.variables;
// Make sure the first letter of the name is capitalized.
sv.name = sv.name.toUpperFirst();