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:

1
2
3
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:

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

Expressions:

You can also place expressions in your template string:

1
2
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:

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

Multi-line support

This also has some support for multi-line string support

1
2
3
4
5
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:

1
2
3
4
5
let multiline = 
  `some multiline
  string here`

console.log(multiline)

is equivalent to doing this:

1
2
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.

1
2
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.

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