Suppose I have a string like "${a + b}", say read from JSON, that I'd like interpreted as an ES6 template literal. I thought something like this might work:
var x = {"add": "${a + b}"};
var a = 10, b = 20;
alert(`${x.add}`);
But this alerts as ${a + b}, so it just does one level of substitution.
Tried being clever by interpreting it again:
var a = 10, b = 20;
var x = {"add": "${a + b}"};
var i = `${x.add}`;
alert(`${i}`);
This still alerts as ${a + b}.
Tried being even more clever:
var a = 10, b = 20;
var x = {"add": "${a} + ${b}"};
var i = `${x.add}`;
alert(`${i}`);
This alerts as ${a} + ${b}.
Starting with a string, e.g. "${a + b}", is there any way to have this evaluated to completion as if it were a template literal? Ideally without eval!
Yes, they aren't recursive.
If your starting point is a string containing those placeholders, as far as I know there is no template compiler function. There's eval, of course; [insert all the usual caveats about using eval — only with content you trust, not if you can avoid it, etc., etc. — here].
So for instance:
"use strict";
var x = {"add": "${a + b}"};
var a = 10, b = 20;
console.log(eval("`" + x.add + "`"));
Related
I'm making a calculator, and I was just wondering if you could have eval() do calculus. I just thought that it would be cool if it could. Thanks in advance!
Try,
var x = 10;
var y = 20;
var a = eval("x * y") + "<br>";
var b = eval("2 + 2") + "<br>";
var c = eval("x + 17") + "<br>";
var res = a + b + c;
The result of res will be:- 200 4 27
Thanks,
Abhilash
eval function evaluates javascript so yes, it will do what you are asking. However, you are most likely do not even need to use it.
Do not call eval() to evaluate an arithmetic expression; JavaScript evaluates arithmetic expressions automatically.
reference
Consider the following :
var a = 5;
var b = function ()
{
console.log (a + 5);
};
var c = b.toString();
after the above has been executed, c will be equal to :
"function ()
{
console.log (a + 5);
}"
How can I have c be equal to :
"function ()
{
console.log (5 + 5);
}"
instead?
I tried the following :
var a = 5;
var b = function ()
{
console.log ('<%a%>' + 5);
};
var c = b.toString().replace('<%a%>', a);
But the above obviously makes c equal to :
"function ()
{
console.log ('5' + 5);
}"
Is there some other way of achieving this (javascript + RegEx) without using libraries like underscore (with the known template function) ?
Basically I'm trying to come up with a neat function that will convert a function into a string while at the same time replacing all variables (that have a hardcoded value) present in that function with their respective values, without the use of any variables.
Thanks
You can fix your snippet by changing the first argument of .replace:
var a = 5;
var b = function ()
{
console.log ('<%a%>' + 5);
};
var c = b.toString().replace("'<%a%>'", a);
For more generic solution you may need smarter parser with syntactical analysis.
For some reason my code returns "0111" when the returned value should be 3 adding the numbers together.
Is there a better way to write this so it adds the value of the input text?
var p = $(".p").val();
var r = $(".r").val();
var d = $(".d").val();
var s = $(".s").val();
var checkability = p + r + d + s;
alert(checkability)
You are concatenating strings you need to cast it to numeric. val() return data as string, or explicitly use parseInt(var, 10) or parseFloat based on your type.
Simple way is t use unary + operator prefixing the variable:
var checkability = +p + +r + +d + +s;
Fiddle
Sure, the easiest thing is to coerce the string values into integers like:
var p = +$(".p").val();
var r = +$(".r").val();
var d = +$(".d").val();
var s = +$(".s").val();
jsFiddle example
You could also use the longer parseInt() function like var p = parseInt( $(".p").val(), 10);
Use parseInt to make them integers
var p = parseInt($(".p").val(),10);
var r = parseInt($(".r").val(),10);
var d = parseInt($(".d").val(),10);
var s = parseInt($(".s").val(),10);
var checkability = p + r + d + s;
alert(checkability)
I would like to join a js variable together with another to create another variable name... so it would be look like;
for (i=1;i<=2;i++){
var marker = new google.maps.Marker({
position:"myLatlng"+i,
map: map,
title:"title"+i,
icon: "image"+i
});
}
and later on I have
myLatlng1=xxxxx;
myLatlng2=xxxxx;
Use the concatenation operator +, and the fact that numeric types will convert automatically into strings:
var a = 1;
var b = "bob";
var c = b + a;
ES6 introduce template strings for concatenation. Template Strings use back-ticks (``) rather than the single or double quotes we're used to with regular strings. A template string could thus be written as follows:
// Simple string substitution
let name = "Brendan";
console.log(`Yo, ${name}!`);
// => "Yo, Brendan!"
var a = 10;
var b = 10;
console.log(`JavaScript first appeared ${a+b} years ago. Crazy!`);
//=> JavaScript first appeared 20 years ago. Crazy!
warning! this does not work with links.
var variable = 'variable',
another = 'another';
['I would', 'like to'].join(' ') + ' a js ' + variable + ' together with ' + another + ' to create ' + [another, ...[variable].concat('name')].join(' ').concat('...');
You can use the JavaScript String concat() Method,
var str1 = "Hello ";
var str2 = "world!";
var res = str1.concat(str2); //will return "Hello world!"
Its syntax is:
string.concat(string1, string2, ..., stringX)
if you want to concatenate the string representation of the values of two variables, use the + sign :
var var1 = 1;
var var2 = "bob";
var var3 = var2 + var1;//=bob1
But if you want to keep the two in only one variable, but still be able to access them later, you could make an object container:
function Container(){
this.variables = [];
}
Container.prototype.addVar = function(var){
this.variables.push(var);
}
Container.prototype.toString = function(){
var result = '';
for(var i in this.variables)
result += this.variables[i];
return result;
}
var var1 = 1;
var var2 = "bob";
var container = new Container();
container.addVar(var2);
container.addVar(var1);
container.toString();// = bob1
the advantage is that you can get the string representation of the two variables, bit you can modify them later :
container.variables[0] = 3;
container.variables[1] = "tom";
container.toString();// = tom3
I am writing a string parser that takes input like "{x} + 20" and evaluates the lexical value of x with the sum of 20 and returns. So
var x = 10;
var new = eval("{x} + 20".replace("/\{(\w+\}/g", "$1"));
and here "new" should equal 30.
How can this be done?
I believe you just do this:
var x = 10
var y = eval("x + 20")
No?