[Solved-6 Solutions] Creating multiline string in javascript - javascript tutorial



Problem:

How to create multiline string in javascript ?

Solution 1:

This is some multi-lined string using a comment inside a function returned as a string.

 var myString = function(){
    }.toString().slice(14,-3)

alert(myString)

Solution 2:

ECMAScript 6 (ES6) introduces as template literals. They have many features, variable interpolation among others, they can be created multiline in string. It is delimited by backticks:

var html = `
  <div>
    <span>Some HTML here</span>
  </div>
`;

Solution 3:

Using ES6/Babel, to a create multi-line strings simply by using backticks:

var htmlString = `Say hello to 
multi-line
strings!`;

Interpolating variables is the feature that comes with back-tick delimited strings:

const htmlString = `${user.name} liked your post about strings`;

Using transpiles down to concatenation:

user.name + ' liked your post about strings'

Solution 4:

The pattern text = <<"HERE" This Is A Multiline String HERE is not available in js. This pattern have some complex or long multiline strings that time we are using an array pattern:

var myString = 
   ['<div id="someId">',
    'some content<br />',
    '<a href="#someRef">someRefTxt</a>',
    '</div>'
   ].join('\n');

The pattern anonymous already showed.

    var myString = 
       '<div id="someId"> \
some content<br /> \
<a href="#someRef">someRefTxt</a> \
</div>';

Use this code:

var myString = (function () {/*
   <div id="someId">
     some content<br />
     <a href="#someRef">someRefTxt</a>
    </div>        
*/}).toString().match(/[^]*\/\*([^]*)\*\/\}$/)[1];

ES20xx is supports as spanning strings for multiple lines instead of using template strings:

let str = `This is a text
    with multiple lines.
    Escapes are interpreted,
    \n is a newline.`;
let str = String.raw`This is a text
    with multiple lines.
    Escapes are not interpreted,
    \n is not a newline.`;

Solution 5:

This code is based on the serialization. It is defined to be implementation-dependent. It does work in all browsers.

function hereDoc(f) {
  return f.toString().
      replace(/^[^\/]+\/\*!?/, '').
      replace(/\*\/[^\/]+$/, '');
}

Use this code:

var tennysonQuote = hereDoc(function() {/*!
  Theirs not to make reply,
  Theirs not to reason why,
  Theirs but to do and die
*/});

The method has been successfully tested in the following browsers like IE 4 – 10, Opera 9.50 - 12 (not in 9-), Safari 4 - 6 (not in 3-), Chrome 1 – 45, Firefox 17 - 21 (not in 16-), Rekonq 0.7.0 - 0.8.0. A comment starting with /*! will be preserved.

Solution 6:

You can try this:

var string = 'This is\n' +
'a multiline\n' + 
'string';

Related Searches to Creating multiline string in javascript - javascript tutorial