HTML: Markup language
CSS: Styling language
JavaScript: Scripting language
Web APIs: Programming interfaces
All web technology
Learn web development
Discover our tools
Get to know MDN better
このページはコミュニティーの尽力で英語から翻訳されました。MDN Web Docs コミュニティーについてもっと知り、仲間になるにはこちらから。
View in English Always switch to English
This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2015年7月.
slice() は String 値のメソッドで、元の文字列を変更せず、文字列の一部分を取り出し、それを新しい文字列として返します。
slice()
String
const str = "The quick brown fox jumps over the lazy dog."; console.log(str.slice(31)); // 予想される結果: "the lazy dog." console.log(str.slice(4, 19)); // 予想される結果: "quick brown fox" console.log(str.slice(-4)); // 予想される結果: "dog." console.log(str.slice(-9, -5)); // 予想される結果: "lazy"
slice(indexStart) slice(indexStart, indexEnd)
indexStart
返却する部分文字列に含める最初の文字の位置です。
indexEnd
返却する部分文字列から除外する最初の文字の位置です。
文字列の取り出された部分を含んだ新しい文字列です。
slice() は 1 つの文字列からテキストを取り出し、新しい文字列を返します。
slice() は、indexEnd まで(ただし indexEnd 自体は含まない)を抽出します。例えば、str.slice(4, 8) は、5 文字目から 8 文字目(インデックス 4、5、6、7 の文字)を抽出します。
str.slice(4, 8)
4
5
6
7
indexStart indexEnd ↓ ↓ | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | | T | h | e | | m | i | r | r | o | r | m i r r _______________ ↑ Result
indexStart >= str.length
indexStart < 0
max(indexStart + str.length, 0)
undefined
0
indexEnd >= str.length
indexEnd < 0
max(indexEnd + str.length, 0)
indexEnd <= indexStart
以下の例では、新しい文字列を生成するために slice() を使っています。
const str1 = "The morning is upon us."; // The length of str1 is 23. const str2 = str1.slice(1, 8); const str3 = str1.slice(4, -2); const str4 = str1.slice(12); const str5 = str1.slice(30); console.log(str2); // he morn console.log(str3); // morning is upon u console.log(str4); // is upon us. console.log(str5); // ""
下記の例では負の位置で slice() を使っています。
const str = "The morning is upon us."; str.slice(-3); // 'us.' str.slice(-3, -1); // 'us' str.slice(0, -1); // 'The morning is upon us' str.slice(4, -1); // 'morning is upon us'
この例では、文字列の末尾から前方に 11 番目を開始位置とし、先頭から後方に 16 番目を終了位置とします。
11
16
console.log(str.slice(-11, 16)); // "is u"
こちらは先頭から後方に 11 番目を開始位置とし、末尾から前方に 7 番目を終了位置とします。
console.log(str.slice(11, -7)); // " is u"
これらの引数は、末尾から前方に 5 番目を開始位置とし、末尾から前方に 1 番目を終了位置とします。
1
console.log(str.slice(-5, -1)); // "n us"
Enable JavaScript to view this browser compatibility table.
String.prototype.substr()
String.prototype.substring()
Array.prototype.slice()