--- title: String.prototype.startsWith() slug: Web/JavaScript/Reference/Global_Objects/String/startsWith tags: - ECMAScript 2015 - JavaScript - Method - Prototype - Reference - String translation_of: Web/JavaScript/Reference/Global_Objects/String/startsWith ---
startsWith() メソッドは文字列が引数で指定された文字列で始まるかを判定して true か false を返します。
このデモのソースファイルは GitHub リポジトリに格納されています。デモプロジェクトに協力したい場合は、 https://github.com/mdn/interactive-examples をクローンしてプルリクエストを送信してください。
str.startsWith(searchString[, position])
searchStringposition {{optional_inline}}searchString を検索し始めるこの文字列の中の位置です。既定値は 0 です。文字列が指定された文字列で始まる場合は true、それ以外の場合は false です。
文字列が特定の文字列で始まるかどうかを判断できます。(英文字の)大文字・小文字は区別されます。
//startswith
let str = 'To be, or not to be, that is the question.'
console.log(str.startsWith('To be')) // true
console.log(str.startsWith('not to be')) // false
console.log(str.startsWith('not to be', 10)) // true
このメソッドは ECMAScript 2015 で追加されました。すべてのJavaScriptの実装でまだ利用可能ではないかもしれません。しかしながら、次のコードでString.prototype.startsWith()をエミュレートできます。
if (!String.prototype.startsWith) {
Object.defineProperty(String.prototype, 'startsWith', {
value: function(search, rawPos) {
var pos = rawPos > 0 ? rawPos|0 : 0;
return this.substring(pos, pos + search.length) === search;
}
});
}
少々重いですがより強力 (ES2015に完全準拠) な互換実装を Mathias Bynens が GitHub で公開しています。
| 仕様書 |
|---|
| {{SpecName('ESDraft', '#sec-string.prototype.startswith', 'String.prototype.startsWith')}} |
{{Compat("javascript.builtins.String.startsWith")}}