Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript backtick multiline string not working in Internet Explorer

I have a large HTML string contained in a var. I'm using it to write to innerHTML.

The first example (with backtick syntax), which is the simplest, does not work in Internet Explorer 11.

Is there a way to get the first example to work in Internet Explorer 11 without having to use an array or newline characters?

Does not work in Internet Explorer

Backtick `

https://jsfiddle.net/qLm02vks/

<div id="display"></div>

var message = `
  <p>this</p>
  <p>is</p>
  <p>a</p>
  <p>multiline</p>
  <p>string</p>
`;

// Write Message
var display = document.getElementById('display');
display.innerHTML = message;

Works in Internet Explorer

Array Join

https://jsfiddle.net/3aytojjf/

var message =
   ['<p>this</p>',
    '<p>is</p>',
    '<p>a</p>',
    '<p>multiline</p>',
    '<p>string</p>'
   ].join('\n');

Works in Internet Explorer

Single quote ' with linebreak \

https://jsfiddle.net/5qzLL4j5/

var message =
'<p>this</p> \
<p>is</p> \
<p>a</p> \
<p>multiline</p> \
<p>string</p>'
 ;
like image 675
Matt McManis Avatar asked Feb 27 '17 18:02

Matt McManis


2 Answers

Problem

The backtick syntax for a string is a Template Literal, which allows for interpolation of variables within a string and multiline strings. They are not supported by Internet Explorer 11 (see more here: ECMAScript 6 compatibility table).

Solution

  1. You can use a transpiler, such as the ever-popular Babel. This will convert the template literal into the ECMAScript 5 syntax that Internet Explorer 11 understands.
  2. You could opt-out of supporting Internet Explorer 11, and stick with support for Edge and other browsers that have native ECMAScript 6 support, though this is usually not an option.
like image 153
Joshua Kleveter Avatar answered Nov 05 '22 07:11

Joshua Kleveter


It is not the most elegant solution, but I solved this myself by minifying my multiline template (Vue) string, and encompassing it within single quotes instead of back ticks. This can be automated as part of the build step, so your code still looks legible for development.

Also ensure that any inner strings (like classNames, etc.) are double quoted so you don't accidentally terminate the string, thereby causing template errors.

like image 44
Gautham Nookala Avatar answered Nov 05 '22 08:11

Gautham Nookala