JavaScript文字列substr()
例
テキストから部分文字列を抽出します。
let text = "Hello world!";
let result = text.substr(1, 4);"
位置2から開始します。
let result = text.substr(2);
以下のその他の例。
定義と使用法
このsubstr()
メソッドは、文字列の一部を抽出します。
このsubstr()
メソッドは指定された位置から始まり、指定された文字数を返します。
このsubstr()
メソッドは元の文字列を変更しません。
文字列の末尾から文字を抽出するには、負の開始位置を使用します。
構文
string.substr(start, length)
パラメーター
Parameter | Description |
start | Required. The start position. First character is at index 0. If start is greater than the length, substr() returns "". If start is negative, substr() counts from the end of the string. |
length | Optional. The number of characters to extract. If omitted, it extracts the rest of the string |
戻り値
タイプ | 説明 |
文字列 | 抽出された部分を含む文字列。長さ が0または負の場合 、空の文字列が返されます。 |
その他の例
最初のみ:
let result = text.substr(0, 1);
最後のみ:
let result = text.substr(text.length-1, 1);
最後の6:
let result = text.substr(-5, 5);
ブラウザのサポート
substr()
ECMAScript1(ES1)機能です。
ES1(JavaScript 1997)は、すべてのブラウザーで完全にサポートされています。
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | Yes | Yes | Yes | Yes | Yes |