6. 新しい文字列機能
目次
本書をサポートしていただけますと幸いです:購入 (PDF、EPUB、MOBI) または 寄付
(広告、ブロックしないでください。)

6. 新しい文字列機能



6.1 概要

新しい文字列メソッド

> 'hello'.startsWith('hell')
true
> 'hello'.endsWith('ello')
true
> 'hello'.includes('ell')
true
> 'doo '.repeat(3)
'doo doo doo '

ES6には、テンプレートリテラルという新しい種類の文字列リテラルがあります。

// String interpolation via template literals (in backticks)
const first = 'Jane';
const last = 'Doe';
console.log(`Hello ${first} ${last}!`);
    // Hello Jane Doe!

// Template literals also let you create strings with multiple lines
const multiLine = `
This is
a string
with multiple
lines`;

6.2 Unicodeコードポイントエスケープ

ECMAScript 6では、任意のコードポイント(16ビットを超えるものも含む)を指定できる新しい種類のUnicodeエスケープがあります。

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

エスケープの詳細については、Unicodeに関する章を参照してください。

6.3 文字列補間、複数行文字列リテラル、およびraw文字列リテラル

テンプレートリテラルについては、独自の章で詳しく説明しています。3つの興味深い機能を提供します。

まず、テンプレートリテラルは文字列補間をサポートしています。

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

次に、テンプレートリテラルには複数行を含めることができます。

const multiLine = `
This is
a string
with multiple
lines`;

最後に、テンプレートリテラルは、タグString.rawをプレフィックスとして付けることで「raw」になります。バックスラッシュは特別な文字ではなく、\nなどのエスケープは解釈されません。

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

6.4 文字列の反復処理

文字列は反復可能であるため、for-ofを使用して文字を反復処理できます。

for (const ch of 'abc') {
    console.log(ch);
}
// Output:
// a
// b
// c

また、スプレッド演算子(...)を使用して、文字列を配列に変換できます。

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

6.4.1 反復処理はUnicodeコードポイントを考慮する

文字列イテレータは、コードポイントの境界で文字列を分割します。つまり、返される文字列は1つまたは2つのJavaScript文字で構成されます。

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

6.4.2 コードポイントの計数

反復処理により、文字列内のUnicodeコードポイントをすばやくカウントできます。

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

6.4.3 BMP以外のコードポイントを含む文字列の反転

反復処理は、BMP以外のコードポイント(16ビットより大きく、2つのJavaScript文字としてエンコードされる)を含む文字列の反転にも役立ちます。

const str = 'x\uD83D\uDE80y';

// ES5: \uD83D\uDE80 are (incorrectly) reversed
console.log(str.split('').reverse().join(''));
    // 'y\uDE80\uD83Dx'

// ES6: order of \uD83D\uDE80 is preserved
console.log([...str].reverse().join(''));
    // 'y\uD83D\uDE80x'
The two reversed strings in the Firefox console.
Firefoxコンソールでの2つの反転された文字列。

6.5 コードポイントの数値

新しいメソッドcodePointAt()は、文字列内の特定のインデックスにあるコードポイントの数値を返します。

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

このメソッドは、文字列の反復処理と組み合わせると効果的です。

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

codePointAt()の反対はString.fromCodePoint()です。

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

6.6 包含の確認

3つの新しいメソッドは、ある文字列が別の文字列内に存在するかどうかを確認します。

> 'hello'.startsWith('hell')
true
> 'hello'.endsWith('ello')
true
> 'hello'.includes('ell')
true

これらのメソッドには、オプションの2番目のパラメータとして位置があり、検索対象の文字列の開始位置または終了位置を指定します。

> 'hello'.startsWith('ello', 1)
true
> 'hello'.endsWith('hell', 4)
true

> 'hello'.includes('ell', 1)
true
> 'hello'.includes('ell', 2)
false

6.7 文字列の繰り返し

repeat()メソッドは文字列を繰り返します。

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

6.8 正規表現の処理をパラメータに委譲する文字列メソッド

ES6では、正規表現パラメータを受け取る4つの文字列メソッドは比較的少量の処理を行います。主にパラメータのメソッドを呼び出します。

パラメータは正規表現である必要がなくなりました。適切なメソッドを持つ任意のオブジェクトで機能します。

6.9 参照:新しい文字列メソッド

タグ付きテンプレート

Unicodeとコードポイント

文字列の検索

文字列の繰り返し

次へ:7. シンボル