user7621398
user7621398

Reputation:

javascript text interpreted as a script

I do not understand the error that comes back to me the browser I put some simple text into a variable but in fact, this is interpreted as a script?

error :

Uncaught SyntaxError: Invalid or unexpected token : line 10

<!DOCTYPE html>
<html lang="en"> 
<head>
<meta charset="utf-8"/>

<body>
</body>
<script>

var text = '<script> Hello </script>' ;

//console.log ( text ); 

</script>
</html>

similar issues: javascript string interpreted as object

Upvotes: 1

Views: 96

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074148

When the browser is parsing that, it sees <script> and blindly builds up text until it sees the sequence </script>, which it then takes as the end of the script. In your case, that's in the middle of your string.

To avoid that, add a backslash in the string before the /:

var text = '<script> Hello <\/script>' ;

That backslash has no effect in JavaScript (an escaped / is still a /), but the browser won't see that as the end of the script.

Or you can break it up:

var text = '<script> Hello <' + '/script>' ;

Basically anything so that the browser doesn't see </script> prior to the actual end of your script.

Upvotes: 4

Related Questions