Create expressions in strings [closed]

0

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.

    
asked by anonymous 19.03.2018 / 19:36

2 answers

0

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

    
19.03.2018 / 20:49
1

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);
    
19.03.2018 / 19:45