[JavaScript]文字列(string)の指定位置の文字を削除するには?

JavaScript

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

文字列(string)の指定位置の文字を削除する方法を紹介します。

スポンサーリンク

方法

文字列(string)の指定位置の文字を削除する方法は、2つあります。

slice()

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

まず、「+」の左辺と右辺で、文字列からslice()を呼び出します。

左辺のslice()の第1引数に「0」、第2引数に「position – 1」(position=削除する位置)を指定します。

右辺のslice()の引数に削除する位置を指定します。

//text=対象の文字列, position=削除する位置(N文字目)
let result = text.slice(0, position - 1) + text.slice(position);

上記の「+」演算子は、呼び出した文字列(string)の指定位置を削除した文字列を生成します。

使用例

let text = "Hello,World"

//6文字目を削除
let position = 6;
let result = text.slice(0, position - 1) + text.slice(position);

console.log(result);
出力:
HelloWorld

substring()

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

まず、「+」の左辺と右辺で、文字列からsubstring()を呼び出します。

左辺のsubstring()の第1引数に「0」、第2引数に「position – 1」(position=削除する位置)を指定します。

右辺のsubstring()の引数に削除する位置を指定します。

//text=対象の文字列, position=削除する位置(N文字目)
let result = text.substring(0, position - 1) + text.substring(position);

上記の「+」演算子は、呼び出した文字列(string)の指定位置を削除した文字列を生成します。

使用例

let text = "Hello,World"

//6文字目を削除
let position = 6;
let result = text.substring(0, position - 1) + text.substring(position);

console.log(result);
出力:
HelloWorld

まとめ

文字列(string)の指定位置の文字を削除する方法は、次の2つです。

  • slice()を使う方法
    let result = text.slice(0, position - 1) + text.slice(position);
  • substring()を使う方法
    let result = text.substring(0, position - 1) + text.substring(position);

コメント

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