Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unterminated string literal / Invalid or unexpected token

Tags:

javascript

Why am I getting...

SyntaxError: unterminated string literal

...in Firefox and...

Uncaught SyntaxError: Invalid or unexpected token

...in Chrome when I run...

$(document).ready(function () {
  function addJSBeforeEndBody(code) {
       $('body').append('<script>' + code + '</script>');
  }
  addJSBeforeEndBody('$(document).ready(function() { console.log("I never end up here."); });');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
like image 331
erikvimz Avatar asked Dec 16 '22 01:12

erikvimz


1 Answers

Break up the string "</script>" (in the javascript code); it will be interpreted as an actual closing script tag rather than the string literal you intend.

$(document).ready(function () {
  function addJSBeforeEndBody(code) {
       $('body').append('<script>' + code + '</scr' + 'ipt>');
  }
  addJSBeforeEndBody('$(document).ready(function() { console.log("It works now."); });');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
like image 187
Dave Newton Avatar answered Jan 06 '23 12:01

Dave Newton