Skip to content

Instantly share code, notes, and snippets.

@surganov
Created April 15, 2015 16:01
Show Gist options
  • Save surganov/019dfff469fc8303e327 to your computer and use it in GitHub Desktop.
Save surganov/019dfff469fc8303e327 to your computer and use it in GitHub Desktop.
Template Strings

PATTERNS

  • interpolation
    • placeholder variable or property
    • math expressions
    • function invocation
    • another template strings
    • HTML
  • multiline
    • compare with es5
    • indents
  • it's just strings
    • concatenation
    • methods
    • escape backticks
  • String.raw
    • escape sequences
    • regexp
  • errors
    • ${} -> #{}
    • indents
    • plain quotes

REFERENCE

CODE

CODE SAMPLES

`My name is ${ person }`

// Wrong interpolation
${} -> #{}

// Basic literal string creation
`In JavaScript '\n' is a line-feed.`

// Multiline strings
`In JavaScript this is
 not legal.`

// String interpolation
var name = "Bob", time = "today";
`Hello ${name}, how are you ${time}?`

// Construct an HTTP request prefix is used to interpret the replacements and construction
GET`http://foo.org/bar?a=${a}&b=${b}
    Content-Type: application/json
    X-Credentials: ${credentials}
    { "foo": ${foo},
      "bar": ${bar}}`(myOnReadyStateChangeHandler);

var s = `a
    b
    c`;
assert(s === 'a\n    b\n    c');

console.log(`23`);

var x = 1;
var y = 2;
`${ x } + ${ y } = ${ x + y}`  // "1 + 2 = 3"

String.raw `a\n${ 42 }b`  // "a\\n42b"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment