String in ES6 has a few new tricks up it’s sleeve’s and I love it. String now supports templating and it is now also iterable – which is a pretty big deal if you’re into String parsing.

Templating

Usage:

let name = 'John'
let hello = `hello ${name}`
console.log(hello)

The only way to do the same thing in ES5 would be through string concatenation:

var name = 'John';
var hello = 'hello ' + name;
console.log(hello);

Expressions:

You can also place expressions in your template string:

let exp = '1 + 1'
console.log(`The result of expression ${exp} is ${eval(exp)}`)

The expression isn’t restricted to any type of expression, so you can make function calls directly in your template:

console.log(`Functions' result : ${(() => 1 + 1 + 5 )()}`)
let f = () => 1 + 1 + 5
console.log(`Functions' result : ${f()}`)

Multi-line support

This also has some support for multi-line string support

let multiline = 
`some multiline
string here`

console.log(multiline)

Caveat

Beware, the multi-line considers all your literal characters e.g. tabs and spaces. So for example:

let multiline = 
  `some multiline
  string here`

console.log(multiline)

is equivalent to doing this:

var multiline = "some multiline\n\tstring here"
console.log(multiline)

Escaping

Escaping can be done as previously before. Just put \ before the character that you need to escape.

let escaped = `we can escape \` and also \${}`
console.log(escaped)

Iterable

String’s are now iterable – if you do plenty of parsing, you will definitely make great use of this.

let str = '1+1'
for(let s in str) {
  console.log(s)
}