Suppose I have the following string:
const str = 'Eu sou
@if (1 + 1 === 2):
um dois
@endif
!';
How do I run expressions like that if
?
I do not want a solution to that problem, just the right way to do it.
Suppose I have the following string:
const str = 'Eu sou
@if (1 + 1 === 2):
um dois
@endif
!';
How do I run expressions like that if
?
I do not want a solution to that problem, just the right way to do it.
Friend,
Since you use 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 - link
You can use the eval () function. This function evaluates javascript codes stored in string.
In your case:
const str = 'if (1 + 1 === 2) {alert(\'um dois\');}';
eval(str);