新しい文字列メソッド
> '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`;
ECMAScript 6では、任意のコードポイント(16ビットを超えるものも含む)を指定できる新しい種類のUnicodeエスケープがあります。
console.log('\u{1F680}'); // ES6: single code point
console.log('\uD83D\uDE80'); // ES5: two code units
エスケープの詳細については、Unicodeに関する章を参照してください。
テンプレートリテラルについては、独自の章で詳しく説明しています。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
文字列は反復可能であるため、for-ofを使用して文字を反復処理できます。
for (const ch of 'abc') {
console.log(ch);
}
// Output:
// a
// b
// c
また、スプレッド演算子(...)を使用して、文字列を配列に変換できます。
const chars = [...'abc'];
// ['a', 'b', 'c']
文字列イテレータは、コードポイントの境界で文字列を分割します。つまり、返される文字列は1つまたは2つのJavaScript文字で構成されます。
for (const ch of 'x\uD83D\uDE80y') {
console.log(ch.length);
}
// Output:
// 1
// 2
// 1
反復処理により、文字列内のUnicodeコードポイントをすばやくカウントできます。
> [...'x\uD83D\uDE80y'].length
3
反復処理は、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'
新しいメソッド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
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
repeat()メソッドは文字列を繰り返します。
> 'doo '.repeat(3)
'doo doo doo '
ES6では、正規表現パラメータを受け取る4つの文字列メソッドは比較的少量の処理を行います。主にパラメータのメソッドを呼び出します。
String.prototype.match(regexp)は呼び出します。regexp[Symbol.match](this).String.prototype.replace(searchValue, replaceValue)は呼び出します。searchValue[Symbol.replace](this, replaceValue).String.prototype.search(regexp)は呼び出します。regexp[Symbol.search](this).String.prototype.split(separator, limit)は呼び出します。separator[Symbol.split](this, limit).パラメータは正規表現である必要がなくなりました。適切なメソッドを持つ任意のオブジェクトで機能します。
タグ付きテンプレート
String.raw(callSite, ...substitutions) : string > String.raw`\n` === '\\n'
true
詳細については、テンプレートリテラルに関する章を参照してください。
Unicodeとコードポイント
String.fromCodePoint(...codePoints : number[]) : stringString.prototype.codePointAt(pos) : numberposから始まるコードポイントの数値を返します(1つまたは2つのJavaScript文字で構成されます)。String.prototype.normalize(form? : string) : string'NFC'形式が推奨されます。文字列の検索
String.prototype.startsWith(searchString, position=0) : booleansearchStringで始まりますか?positionを使用すると、チェック対象の文字列の開始位置を指定できます。String.prototype.endsWith(searchString, endPosition=searchString.length) : booleansearchStringで終わりますか?endPositionを使用すると、チェック対象の文字列の終了位置を指定できます。String.prototype.includes(searchString, position=0) : booleansearchStringを含みますか?positionを使用すると、検索対象の文字列の開始位置を指定できます。文字列の繰り返し
String.prototype.repeat(count) : stringcount回連結して返します。