I want to make a website in which variable name written in ‘{{‘ and ‘}}’ should get the value of variable. For example
JavaScript
x
7
1
<body>
2
hi its is {{ a }}
3
<script>
4
var a = me;
5
</script>
6
</body>
7
the output should be hi its is computer
here is my code.
JavaScript
1
26
26
1
<!DOCTYPE html>
2
<html lang="en">
3
<head>
4
<meta charset="UTF-8">
5
<meta http-equiv="X-UA-Compatible" content="IE=edge">
6
<meta name="viewport" content="width=device-width, initial-scale=1.0">
7
<title>Document</title>
8
</head>
9
<body>
10
hey it is {{ data[0] }}. how are you. I am {{ data[1] }} years old.
11
<script>
12
var data = ["computer",'2000'];
13
//the script
14
var doc = document.body.innerHTML;
15
let length = doc.split('{{').length-4;
16
for(let i=1;i<=length;i++){
17
let dos = doc.slice(doc.search('{{')+2,doc.search('}}'));
18
eval(`sp = ${dos}`);
19
document.body.innerHTML = doc.replace(dos,sp).replace('{{','').replace('}}','');
20
var sp = '';
21
}
22
//the end of script
23
</script>
24
</body>
25
</html>
26
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
JavaScript
1
2
1
document.body.innerHTML = doc.replace
2
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
JavaScript
1
14
14
1
var data = ["computer", '2000'];
2
//the script
3
var doc = document.body.innerHTML;
4
let length = doc.split('{{').length - 4;
5
for (let i = 1; i <= length; i++) {
6
let dos = doc.slice(doc.search('{{') + 2, doc.search('}}'));
7
console.log(dos)
8
eval(`sp = ${dos}`);
9
document.body.innerHTML = doc.replace(dos, sp).replace('{{', '').replace('}}', '');
10
11
// update the doc variable
12
doc = document.body.innerHTML;
13
var sp = '';
14
}
JavaScript
1
1
1
hey it is {{ data[0] }}. how are you. I am {{ data[1] }} years old.