I am building a code-editor, and below is my code:
JavaScript
x
65
65
1
<template>
2
<div>
3
<textarea
4
id="html"
5
placeholder="HTML"
6
></textarea>
7
<textarea
8
id="css"
9
placeholder="CSS"
10
></textarea>
11
<textarea
12
id="js"
13
placeholder="JavaScript"
14
></textarea>
15
<iframe id="code"></iframe>
16
</div>
17
</template>
18
19
<script>
20
export default {
21
name: 'code-editor',
22
mounted () {
23
this.compile();
24
},
25
methods: {
26
compile () {
27
var html = document.getElementById("html");
28
var css = document.getElementById("css");
29
var js = document.getElementById("js");
30
var code = document.getElementById("code").contentWindow.document;
31
32
document.body.onkeyup = function () {
33
code.open();
34
code.writeln(
35
`${html.value} <style> ${css.value} </style> <script> ${js.value} <script> `
36
);
37
code.close();
38
};
39
}
40
}
41
}
42
</script>
43
44
<style>
45
textarea {
46
width: 32%;
47
/* float: top; */
48
min-height: 250px;
49
overflow: scroll;
50
margin: auto;
51
display: inline-block;
52
background: #f4f4f9;
53
outline: none;
54
font-family: Courier, sans-serif;
55
font-size: 14px;
56
}
57
58
iframe {
59
bottom: 0;
60
position: relative;
61
width: 100%;
62
height: 35em;
63
}
64
</style>
65
Inside my onkeyup
function in the writeln
command, with the above string I get this error:
JavaScript
1
9
1
error in ./src/components/CodeEditor.vue?vue&type=script&lang=js&
2
3
Syntax Error: Unterminated template (35:75)
4
5
33 | code.open();
6
34 | code.writeln(
7
> 35 | `${html.value} <style> ${css.value} </style> <script> ${js.value}
8
| ^
9
But then if I remove the </script>
tag from the string it works. I don’t know why it doesn’t accept the close tag.
Can anyone explain this to me? Is there any way to make it accept the </script>
tag?
Advertisement
Answer
You need it to break the </script>
into "<" + "/script>"
so that the HTML parser doesn’t interpret it as the closing tag. You can also do </script>
.
An example of how it works:
JavaScript
1
4
1
<script>
2
console.log("hello </script>");
3
console.log("hello <" + "/script>");
4
</script>
And an example of how it wouldn’t work (with plain </script>
which would be interpreted as the closing tag):
JavaScript
1
3
1
<script>
2
console.log("hello </script>");
3
</script>
And if you want to use it inside back quotes, still the same (adding this per OP’s comment):
JavaScript
1
4
1
<script>
2
let foo = "foo";
3
console.log(`hello ${foo} </script>`);
4
</script>