0
Suppose I have the following string:
const str = `Eu sou
@if (1 + 1 === 2):
um dois
@endif
!`;
How do I execute expressions like that if
?
I don’t want a solution to exactly that problem, just the right way to do it.
0
Suppose I have the following string:
const str = `Eu sou
@if (1 + 1 === 2):
um dois
@endif
!`;
How do I execute expressions like that if
?
I don’t want a solution to exactly that problem, just the right way to do it.
1
You can use the function val(). This function evaluates javascript code stored in string.
In your case:
const str = 'if (1 + 1 === 2) {alert(\'um dois\');}';
eval(str);
0
Friend,
Since you use it const
then you can do something like this:
const str = `Eu sou ${1 + 1 === 2 ? 'um dois' : 'nao sou'}!`;
In other more advanced cases I recommend you use some template language in JS like Handlebars.js - https://handlebarsjs.com/
It also doesn’t solve my problem. I want to know how to do that (code snippet above) work...
Dude, that chunk of code is not Javascript, there’s no @if or @endif syntax in Javascript, it can’t work. You’ll have to adapt your code "chunk" to something Javascript understands OR adapt to some handlebar template language.
Yeah. Handlebars wasn’t a "language" either until it was written. Basically, what I want to do is create a kind of visualization engine (view engine) and I would like to know how to interpret the expressions (as a if
) which are in a string (as in the "chunk" I provided above).
Browser other questions tagged javascript string expressions
You are not signed in. Login or sign up in order to post.
Snippet of code did not work. An error was released.
– Luiz Felipe
It is because your code is giving error. I have updated with a javascript code that makes an Alert.
– Felipe