Multiline strings in JavaScript

Related tags

String deprecated
Overview

multiline Build Status

Multiline strings in JavaScript

No more string concatenation or array join!

Use ES2015 template literals instead whenever possible.

Before

const str = '' +
'<!doctype html>' +
'<html>' +
'	<body>' +
'		<h1>❤ unicorns</h1>' +
'	</body>' +
'</html>' +
'';

After

const str = multiline(()=>{/*
<!doctype html>
<html>
	<body>
		<h1>❤ unicorns</h1>
	</body>
</html>
*/});

How

It works by wrapping the text in a block comment, anonymous function, and a function call. The anonymous function is passed into the function call and the contents of the comment extracted.

Even though it's slower than string concat, that shouldn't realistically matter as you can still do 2 million of those a second. Convenience over micro performance always.

Install

$ npm install multiline

Usage

Everything after the first newline and before the last will be returned as seen below:

const str = multiline(()=>{/*
<!doctype html>
<html>
	<body>
		<h1>❤ unicorns</h1>
	</body>
</html>
*/});

Which outputs:

<!doctype html>
<html>
	<body>
		<h1>❤ unicorns</h1>
	</body>
</html>

Strip indent

You can use multiline.stripIndent() to be able to indent your multiline string without preserving the redundant leading whitespace.

	const str = multiline.stripIndent(()=>{/*
			<!doctype html>
			<html>
				<body>
					<h1>❤ unicorns</h1>
				</body>
			</html>
	*/});

Which outputs:

<!doctype html>
<html>
	<body>
		<h1>❤ unicorns</h1>
	</body>
</html>

String substitution

console.log() supports string substitution:

const str = 'unicorns';

console.log(multiline(()=>{/*
  I love %s
*/}), str);

//=> 'I love unicorns'

Use cases

Have one? Let me know.

Experiment

I've also done an experiment where you don't need the anonymous function. It's too fragile and slow to be practical though.

It generates a callstack and extracts the contents of the comment in the function call.

const str = multiline(/*
<!doctype html>
<html>
	<body>
		<h1>❤ unicorns</h1>
	</body>
</html>
*/);

FAQ

But JS already has multiline strings with \?

const str = 'foo\
bar';

This is not a multiline string. It's line-continuation. It doesn't preserve newlines, which is the main reason for wanting multiline strings.

You would need to do the following:

const str = 'foo\n\
bar';

But then you could just as well concatenate:

const str = 'foo\n' +
'bar';

Browser

While it does work fine in the browser, it's mainly intended for use in Node.js. Use at your own risk.

$ npm install multiline

With Webpack, Browserify, or something similar.

Compatibility

  • Latest Chrome
  • Firefox >=17
  • Safari >=4
  • Opera >=9
  • Internet Explorer >=6

Minification

Even though minifiers strip comments by default there are ways to preserve them:

  • Uglify: Use /*@preserve instead of /* and enable the comments option
  • Closure Compiler: Use /*@preserve instead of /*
  • YUI Compressor: Use /*! instead of /*

You also need to add console.log after the comment so it's not removed as dead-code.

The final result would be:

const str = multiline(function(){/*!@preserve
<!doctype html>
<html>
	<body>
		<h1>❤ unicorns</h1>
	</body>
</html>
*/console.log});

License

MIT © Sindre Sorhus

Comments
  • Adding string interpolation

    Adding string interpolation

    usage:

    name = 'Daniel';
    console.log(multiline(function(){/*
    Hello, $[name], you must be $[20+5] years old.
    */}));
    

    outputs: Hello, Daniel, you must be 25 years old.

    opened by DanielWeiner 10
  • Code based unicode symbols

    Code based unicode symbols

    Do you think it's possible to extend multiline to support unicode characters?

    In my tests I need to prepare multi line text including control characters, like this

    console.log(multiline(function(){/*
    \0
    \u0000
    */}));
    

    But the \ is escaped and displayed as a \, I'd like to insert the \0 control character in the string.

    opened by piuccio 9
  • Error in chinese string

    Error in chinese string

    When I console this

    var welcome = this.yeoman + multiline.stripIndent(function () {/*
      _Project Name_ should not contain "jquery" or "js" and should be a unique ID not already in use at plugins.jquery.com.
    
      _Project title_ should be a human-readable title, and doesn't need to contain the word "jQuery", although it may.
    
      For example, a plugin titled "Awesome Plugin" might have the name "awesome-plugin".
    
      For more information, please see the following documentation: 你們好好好好厲害
    
      Naming Your Plugin      http://plugins.jquery.com/docs/names/
      Publishing Your Plugin  http://plugins.jquery.com/docs/publish/
      Package Manifest        http://plugins.jquery.com/docs/package-manifest/
    */});
    

    the phrase

    For more information, please see the following documentation: 你們好好好好厲害

    is broken

    screen shot 2014-05-02 at 9 51 01 am

    opened by hueitan 5
  • Added stability

    Added stability

    *Pre-minified and post-minified comments are now supported (supports YUI and Closure Compiler syntax) *Comments before "comment body" are ignored *Invalid comment returns a blank string *Moved optional white-space inside non-capture groups

    opened by schooley 5
  • Closure Compiler, Minification strips comments, @preserve / @license not working

    Closure Compiler, Minification strips comments, @preserve / @license not working

    Hello I'm trying to minify js file that uses multiline. I do exacly what you told me in readme, that is starting comment block with @preserve and adding console.log at the end. Unfortunately this is not working :( Please help! Thank You! Safety third! Smoke cigarettes!

    Online Closure Compiler Service: https://closure-compiler.appspot.com/home

    Input:

    var tpl = $(multiline
      .stripIndent(function(){/*@preserve
        Lorem
      */console.log}))
    

    Output:

    $(multiline.a(function(){console.log}));
    

    Expected output:

    $(multiline.a(function(){/*Lorem*/console.log}));
    
    opened by mateuszjarzewski 4
  • Support for `util.format`?

    Support for `util.format`?

    It'd be great to be able to do something like...

    var str = multiline(function(){/*
    <!doctype html>
    <html>
        <body>
            <h1>%s has %d %s</h1>
        </body>
    </html>
    */}, 'Sindre', 4, 'unicorns')
    
    opened by niftylettuce 4
  • Added String interpolation

    Added String interpolation

    Placeholders are replaced with their corresponding values:

    multiline(function(){/*
    <!doctype html>
    <html>
        <body>
            <h1>❤ $name</h1>
        </body>
    </html>
    */}, {
      name: 'unicorns'
    });
    

    Which outputs:

    <!doctype html>
    <html>
        <body>
            <h1>❤ unicorns</h1>
        </body>
    </html>
    
    opened by danilosampaio 3
  • these cases should throw exception

    these cases should throw exception

    this case should throw exception:

    multiline(function () {
    // test invalid content
    /*
    valid content
    */
    });
    

    this case should throw too:

    multiline(function () {
    /*
    valid content
    */
    /*
    valid content 2
    */
    });
    
    opened by fishbar 3
  • Having javascript multiline comments (/* ... */) inside the multiline string

    Having javascript multiline comments (/* ... */) inside the multiline string

    Is it possible to have multiline js style comments (/*... */) in the string? One convoluted use case is having commented CDATA blocks in one's svg markup for css styles.

    multiline(function(){
    /*
    <svg>
    <style>
      /* <![CDATA[ */
        rect {
          fill: salmon;
        }
      /* ]]> */
    </style>
    </svg>
    
    
    */        })
    

    That just generates an expected SyntaxError: Unexpected token < error and non of the escaping i've tried seems to generate the desired comments.

    I can skip the CDATA blocks or put the styles in my separate stylesheets rather than the tag, so this is not blocking, but I was curious about it.

    opened by yuvilio 3
  • How to go without `requirejs`

    How to go without `requirejs`

    Hi! Thank you for useful software.

    I'm using it like this, in an essentially adapted way, because I didn't want to add requirejs as a dependency.

    I'd love to know how a more experienced JavaScript developer would have done it.

    opened by mightyiam 3
  • Strip indentation

    Strip indentation

    Would be nice if this https://github.com/sindresorhus/pageres/blob/50b2a30dbd2335b1e955ad53dc9226bf52ad578d/cli.js#L16-L31 could be indented on the same level as the method, but return a non-indented string.

    Should probably be a separate method.

    enhancement 
    opened by sindresorhus 3
Owner
Sindre Sorhus
Full-Time Open-Sourcerer. Wants more empathy & kindness in open source. Focuses on Swift & JavaScript. Makes macOS apps, CLI tools, npm packages. Likes unicorns
Sindre Sorhus
Parse and stringify URL query strings

query-string Parse and stringify URL query strings My open source work is supported by the community Special thanks to: All your environment variables

Sindre Sorhus 6.2k Jan 9, 2023
The ultimate JavaScript string library

Voca is a JavaScript library for manipulating strings. https://vocajs.com v.camelCase('bird flight'); // => 'birdFlight' v.sprintf('%s co

Dmitri Pavlutin 3.5k Dec 20, 2022
String manipulation helpers for javascript

The stable release documentation can be found here https://epeli.github.io/underscore.string/ Underscore.string Javascript lacks complete string manip

Esa-Matti Suuronen 3.4k Dec 25, 2022
Extra JavaScript string methods.

string.js string.js, or simply S is a lightweight (< 5 kb minified and gzipped) JavaScript library for the browser or for Node.js that provides extra

JP Richardson 1.8k Dec 17, 2022
A robust HTML entity encoder/decoder written in JavaScript.

he he (for “HTML entities”) is a robust HTML entity encoder/decoder written in JavaScript. It supports all standardized named character references as

Mathias Bynens 3.2k Dec 27, 2022
Javascript URL mutation library

URI.js About Understanding URIs Documentation jQuery URI Plugin Author Changelog IMPORTANT: You may not need URI.js anymore! Modern browsers provide t

Medialize 6.2k Dec 30, 2022
Lightweight URL manipulation with JavaScript

domurl 2.x (former jsurl) Lightweight URL manipulation with JavaScript for both DOM and server JavaScript. Goal To have a convenient way working with

Mykhailo Stadnyk 511 Dec 28, 2022
sprintf.js is a complete open source JavaScript sprintf implementation

sprintf-js sprintf-js is a complete open source JavaScript sprintf implementation for the browser and Node.js. Note: as of v1.1.1 you might need some

Alexandru Mărășteanu 2k Jan 4, 2023
easier than regex string matching patterns for urls and other strings. turn strings into data or data into strings.

url-pattern easier than regex string matching patterns for urls and other strings. turn strings into data or data into strings. This is a great little

null 562 Jan 5, 2023
A lightweight JavaScript library that renders text in a brilliant style by displaying strings of random characters before the actual text.

cryptoWriter.js A lightweight javascript library which creates brilliant text animation by rendering strings of random characters before the actual te

Keshav Bajaj 2 Sep 13, 2022
parses human-readable strings for JavaScript's Temporal API

?? temporal-parse What is the temporal-parse? Temporal is the next generation of JavaScript's standard Date API. It's currently proposed to TC39 (see:

Eser Ozvataf 22 Jan 2, 2023
This package will help parse OData strings (only the Microsoft Dataverse subset). It can be used as a validator, or you can build some javascript library which consumes the output of this library.

@albanian-xrm/dataverse-odata This package will help parse OData strings (only the Microsoft Dataverse subset). It can be used as a validator, or you

AlbanianXrm 3 Oct 22, 2022
Parse and stringify URL query strings

query-string Parse and stringify URL query strings My open source work is supported by the community Special thanks to: All your environment variables

Sindre Sorhus 6.2k Jan 9, 2023
Node.js object hash library with properties/arrays sorting to provide constant hashes. It also provides a method that returns sorted object strings that can be used for object comparison without hashes.

node-object-hash Tiny and fast node.js object hash library with properties/arrays sorting to provide constant hashes. It also provides a method that r

Alexander 73 Oct 7, 2022
AnonCrypt ciphers and diciphers your messages or strings which makes you send texts to people without them understanding it.

AnonCrypt ciphers and diciphers your messages or strings which makes you send texts to people without them understanding it. Anoncrypt uses Aes192 cipher encryption type and not Hmac.

AnonyminHack5 11 Oct 23, 2022
A lightweight, locale aware formatter for strings containing unicode date tokens.

Date Token Format A lightweight (~2kB), locale aware formatter for strings containing unicode date tokens. Usage Install the package using: yarn add d

Donovan Hutchinson 1 Dec 24, 2021
Emoji - Use emoji names instead of Unicode strings. Copy-pasting emoji sucks.

Grammy Emoji Adds emoji parsing for grammY. Check out the official documentation for this plugin. While this draft is working, we still do not recomme

null 8 Sep 5, 2022
Compare camelized/dasherized/underscored strings each other 🤜🏿 🤛🏿

aynen Compare camelized/dasherized/underscored strings each other Install npm install aynen yarn add aynen Usage import aynen from 'aynen'; aynen('fo

null 4 Mar 25, 2022
Simple string diffing. Given two strings, striff will return an object noting which characters were added or removed, and at which indices

Simple string diffing. Given two strings, striff will return an object noting which characters were added or removed, and at which indices

Alex MacArthur 196 Jan 6, 2023
A TypeScript namespace declaration for KeyboardEvent.key strings, just in case your code is allergic to enums.

ts-key-namespace A TypeScript namespace declaration for KeyboardEvent.key strings, just in case you prefer namespaces to enums. Largely based on ts-ke

Daniel Soohan Park 3 Apr 5, 2022