Skip to content

Instantly share code, notes, and snippets.

@dfkaye
Last active June 19, 2019 04:28
Show Gist options
  • Save dfkaye/1c7906dce20f3e5f6cf4717aaa04e590 to your computer and use it in GitHub Desktop.
Save dfkaye/1c7906dce20f3e5f6cf4717aaa04e590 to your computer and use it in GitHub Desktop.
3 ways to generate multiline strings in JavaScript
// 16 June 2019
// 3 ways to generate multiline strings in JavaScript
// see also string templates
// https://gist.github.com/dfkaye/088f0d5cc76d387c1357
// and "stateless" components
// https://gist.github.com/dfkaye/2d5cbd87f6bbf4976762
// 1. template literals (es6)
var es6literal = `
This is a multi-
line template literal.
`;
console.log(es6literal.trim());
/*
This is a multi-
line template literal.
*/
// 2. EOL backslash (es3)
var es3string = "\
This is a multi-\
line string\n\
with a newline char.\
";
console.log(es3string.trim());
/*
This is a multi-line string
with a newline char.
*/
// 3. function toString with a regex (es3)
var heredoc = function() {/*!
This comment is a multi-
line string inside
of a function.
!*/}
console.log(String(heredoc).match(/(?:\/\*\!)([^\/]+)(?:\!\*\/)/)[1].trim());
/*
This comment is a multi-
line string inside
of a function.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment