Please support this book: buy it (PDF, EPUB, MOBI) or donate

6. New string features

6.1 Overview

New string methods:

  1. > 'hello'.startsWith('hell')
  2. true
  3. > 'hello'.endsWith('ello')
  4. true
  5. > 'hello'.includes('ell')
  6. true
  7. > 'doo '.repeat(3)
  8. 'doo doo doo '

ES6 has a new kind of string literal, the template literal:

  1. // String interpolation via template literals (in backticks)
  2. const first = 'Jane';
  3. const last = 'Doe';
  4. console.log(`Hello ${first} ${last}!`);
  5. // Hello Jane Doe!
  6.  
  7. // Template literals also let you create strings with multiple lines
  8. const multiLine = `
  9. This is
  10. a string
  11. with multiple
  12. lines`;

6.2 Unicode code point escapes

In ECMAScript 6, there is a new kind of Unicode escape that lets you specify any code point (even those beyond 16 bits):

  1. console.log('\u{1F680}'); // ES6: single code point
  2. console.log('\uD83D\uDE80'); // ES5: two code units

More information on escapes is given in the chapter on Unicode.

6.3 String interpolation, multi-line string literals and raw string literals

Template literals are described in depth in their own chapter. They provide three interesting features.

First, template literals support string interpolation:

  1. const first = 'Jane';
  2. const last = 'Doe';
  3. console.log(`Hello ${first} ${last}!`);
  4. // Hello Jane Doe!

Second, template literals can contain multiple lines:

  1. const multiLine = `
  2. This is
  3. a string
  4. with multiple
  5. lines`;

Third, template literals are “raw” if you prefix them with the tag String.raw – the backslash is not a special character and escapes such as \n are not interpreted:

  1. const str = String.raw`Not a newline: \n`;
  2. console.log(str === 'Not a newline: \\n'); // true

6.4 Iterating over strings

Strings are iterable, which means that you can use for-of to iterate over their characters:

  1. for (const ch of 'abc') {
  2. console.log(ch);
  3. }
  4. // Output:
  5. // a
  6. // b
  7. // c

And you can use the spread operator () to turn strings into Arrays:

  1. const chars = [...'abc'];
  2. // ['a', 'b', 'c']

6.4.1 Iteration honors Unicode code points

The string iterator splits strings along code point boundaries, which means that the strings it returns comprise one or two JavaScript characters:

  1. for (const ch of 'x\uD83D\uDE80y') {
  2. console.log(ch.length);
  3. }
  4. // Output:
  5. // 1
  6. // 2
  7. // 1

6.4.2 Counting code points

Iteration gives you a quick way to count the Unicode code points in a string:

  1. > [...'x\uD83D\uDE80y'].length
  2. 3

6.4.3 Reversing strings with non-BMP code points

Iteration also helps with reversing strings that contain non-BMP code points (which are larger than 16 bit and encoded as two JavaScript characters):

  1. const str = 'x\uD83D\uDE80y';
  2.  
  3. // ES5: \uD83D\uDE80 are (incorrectly) reversed
  4. console.log(str.split('').reverse().join(''));
  5. // 'y\uDE80\uD83Dx'
  6.  
  7. // ES6: order of \uD83D\uDE80 is preserved
  8. console.log([...str].reverse().join(''));
  9. // 'y\uD83D\uDE80x'

The two reversed strings in the Firefox console.

The two reversed strings in the Firefox console.

6.5 Numeric values of code points

The new method codePointAt() returns the numeric value of a code point at a given index in a string:

  1. const str = 'x\uD83D\uDE80y';
  2. console.log(str.codePointAt(0).toString(16)); // 78
  3. console.log(str.codePointAt(1).toString(16)); // 1f680
  4. console.log(str.codePointAt(3).toString(16)); // 79

This method works well when combined with iteration over strings:

  1. for (const ch of 'x\uD83D\uDE80y') {
  2. console.log(ch.codePointAt(0).toString(16));
  3. }
  4. // Output:
  5. // 78
  6. // 1f680
  7. // 79

The opposite of codePointAt() is String.fromCodePoint():

  1. > String.fromCodePoint(0x78, 0x1f680, 0x79) === 'x\uD83D\uDE80y'
  2. true

6.6 Checking for inclusion

Three new methods check whether a string exists within another string:

  1. > 'hello'.startsWith('hell')
  2. true
  3. > 'hello'.endsWith('ello')
  4. true
  5. > 'hello'.includes('ell')
  6. true

Each of these methods has a position as an optional second parameter, which specifies where the string to be searched starts or ends:

  1. > 'hello'.startsWith('ello', 1)
  2. true
  3. > 'hello'.endsWith('hell', 4)
  4. true
  5.  
  6. > 'hello'.includes('ell', 1)
  7. true
  8. > 'hello'.includes('ell', 2)
  9. false

6.7 Repeating strings

The repeat() method repeats strings:

  1. > 'doo '.repeat(3)
  2. 'doo doo doo '

6.8 String methods that delegate regular expression work to their parameters

In ES6, the four string methods that accept regular expression parameters do relatively little. They mainly call methods of their parameters:

  • String.prototype.match(regexp) callsregexpSymbol.match.
  • String.prototype.replace(searchValue, replaceValue) callssearchValueSymbol.replace.
  • String.prototype.search(regexp) callsregexpSymbol.search.
  • String.prototype.split(separator, limit) callsseparatorSymbol.split. The parameters don’t have to be regular expressions, anymore. Any objects with appropriate methods will do.

6.9 Reference: the new string methods

Tagged templates:

  • String.raw(callSite, …substitutions) : stringTemplate tag for “raw” content (backslashes are not interpreted):
  1. > String.raw`\n` === '\\n'
  2. true

Consult the chapter on template literals for more information.

Unicode and code points:

  • String.fromCodePoint(…codePoints : number[]) : stringTurns numbers denoting Unicode code points into a string.
  • String.prototype.codePointAt(pos) : numberReturns the number of the code point starting at position pos (comprising one or two JavaScript characters).
  • String.prototype.normalize(form? : string) : stringDifferent combinations of code points may look the same. Unicode normalization changes them all to the same value(s), their so-called canonical representation. That helps with comparing and searching for strings. The 'NFC' form is recommended for general text. Finding strings:

  • String.prototype.startsWith(searchString, position=0) : booleanDoes the receiver start with searchString? position lets you specify where the string to be checked starts.

  • String.prototype.endsWith(searchString, endPosition=searchString.length) : booleanDoes the receiver end with searchString? endPosition lets you specify where the string to be checked ends.
  • String.prototype.includes(searchString, position=0) : booleanDoes the receiver contain searchString? position lets you specify where the string to be searched starts. Repeating strings:

  • String.prototype.repeat(count) : stringReturns the receiver, concatenated count times.