String

A string is basically a sequence of characters. A string variable can be declared with a string literal or the String object.

A string literal is enclosed within "...", '...', or `...`. The first two forms are interchangeable. They can span multiples by using a \ at the end of lines.

ECMAScript 6 introduces the third form of strings, template literals, which are enclosed within `...`. They can interpolate expressions within. They can also span multiple lines.


var a = '123';
console.log(a);

var b = "a'b'c";
console.log(b);

var c = `${a}`;
console.log(c);

var c = `${a + b}`;
console.log(c);

console.log("hello \
                     world");

console.log(`hello
                      world`);

console.log(`${3 + 4}-eleven`);

123 a'b'c 123 123a'b'c hello world hello world 7-eleven

A template string can be passed to a function without the parentheses, as a tagged template string.


function f(strings, ...values) {
  console.log(strings[0]);
  console.log(strings[1]);
  console.log(strings[2]);
  console.log(values[0]);
  console.log(values[1]);
}

f `a${42}bc${999}d`;

a bc d 42 999

To silence errors caused by invalid Unicode escape sequence, enclose the Unicode within {}.


console.log("\u9999");
// console.log("\u55");   // SyntaxError: Invalid Unicode
console.log("\u{55}");

function tag(s) {
  console.log(s[0]);
  console.log(s[1]);
  console.log(s.raw[0]);
}

tag `\u55 \u{55}`;

香 U undefined undefined \u55 \u{55}

Note that a string is also an iterable.