Skip to content
Advertisement

replace variable name with the respective variable value

I want to make a website in which variable name written in ‘{{‘ and ‘}}’ should get the value of variable. For example

<body>
hi its is {{ a }}
<script>
var a = me;
</script>
</body>

the output should be hi its is computer

here is my code.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    hey it is {{ data[0] }}. how are you. I am {{ data[1] }} years old.
    <script>
        var data = ["computer",'2000'];  
        //the script
        var doc = document.body.innerHTML;
        let length = doc.split('{{').length-4;
        for(let i=1;i<=length;i++){
        let dos = doc.slice(doc.search('{{')+2,doc.search('}}'));
        eval(`sp = ${dos}`);
        document.body.innerHTML = doc.replace(dos,sp).replace('{{','').replace('}}','');
        var sp = '';
    }
        //the end of script
        </script>
        </body>
</html>

output of the above code is: hey it is computer. how are you. I am {{ data[1] }} years old. once visit this jsfiddle. Here is my code. https://jsfiddle.net/3ocmkwq2/

Thanks

Advertisement

Answer

This line

document.body.innerHTML = doc.replace...

updates document.body.innerHTML, but does not update the doc variable, so this remains as it was before any replacements were made.

So next loop, doc is still the original, so the splice to get {{ }} re-gets the data[0].

To fix, update doc= after changing the .innerHTML

var data = ["computer", '2000'];
//the script
var doc = document.body.innerHTML;
let length = doc.split('{{').length - 4;
for (let i = 1; i <= length; i++) {
  let dos = doc.slice(doc.search('{{') + 2, doc.search('}}'));
  console.log(dos)
  eval(`sp = ${dos}`);
  document.body.innerHTML = doc.replace(dos, sp).replace('{{', '').replace('}}', '');
  
  // update the doc variable
  doc = document.body.innerHTML;
  var sp = '';
}
hey it is {{ data[0] }}. how are you. I am {{ data[1] }} years old.
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement