[JavaScript]文字列(string)の特定の範囲を取得するには?

JavaScript

どうも、ちょげ(@chogetarou)です。

文字列(string)の指定した範囲の文字列を取得する方法を紹介します。

スポンサーリンク

方法

文字列(string)の特定の範囲を取得する方法は、2つあります。

slice()

ひとつは、slice()を使う方法です。

まず、文字列からslice()を呼び出します。

そして、slice()の第1引数に範囲の最初の位置、第2引数に範囲の最後の位置を指定します。
(文字の位置は、先頭から0、1、2・・と数えます)

//text=対象の文字列, start=範囲の最初の位置, end=範囲の最後の位置
let result = text.slice(start, end);

上記のslice()は、対象の文字列(string)の第1引数から第2引数までの範囲を取得します。

使用例

let text = "ABCDEFGHIJK";

let result = text.slice(1, 3);
let result2 = text.slice(5, 8);
let result3 = text.slice(0, 5);

console.log(result);
console.log(result2);
console.log(result3);
出力:
BC
FGH
ABCDE

substring()

もうひとつは、substring()を使う方法です。

まず、文字列からsubstring()を呼び出します。

そして、substring()の第1引数に範囲の最初の位置、第2引数に範囲の最後の位置を指定します。
(位置は、先頭から0、1、2・・と数えます)

//text=対象の文字列, start=範囲の最初の位置, end=範囲の最後の位置
let result = text.substring(start, end);

上記のsubstring()は、対象の文字列(string)の第1引数から第2引数までの範囲を取得します。

使用例

let text = "ABCDEFGHIJK";

let result = text.substring(1, 3);
let result2 = text.substring(5, 8);
let result3 = text.substring(0, 5);

console.log(result);
console.log(result2);
console.log(result3);
出力:
BC
FGH
ABCDE
スポンサーリンク

まとめ

文字列(string)の特定の範囲を取得する方法は、次の2つです。

  • slice()を使う方法
    let result = text.slice(start, end);
  • substring()を使う方法
    let result = text.substring(start, end);

コメント

タイトルとURLをコピーしました