[JavaScript]文字列(string)の空白(スペース)を置換するには?

JavaScript

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

文字列(string)の空白(スペース)を置換する方法を紹介します。

スポンサーリンク

方法

文字列(string)の空白(スペース)を置換する方法は、2つあります。

replace()

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

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

そして、replace()の第1引数に「/ /g」(スラッシュの間に空白)、第2引数に置換後の文字を指定します。

//text=対象の文字列, new=置換後の文字列
let result = text.replace(/ /g, new)

上記のreplace()は、呼び出した文字列(string)の空白(スペース)を置換した文字列を生成します。

もし、全角の空白を含めたい場合は、正規表現で半角と全角の両方を指定します。

//半角と全角の両方の空白を置換
let result = text.replace(/[  ]/g, new)

上記のreplace()は、複数の空白が連続して並んでいる場合、1つ1つの空白を別々に置換します。

もし、連続している空白を1つの空白として扱いたい場合は、正規表現の「+」を使います。

let result = text.replace(/ +/g, new)
let result = text.replace(/[  ]+/g, new)

使用例1

let text = " Hello World "

let result = text.replace(/ /g, "/")

console.log(result);
出力:
/Hello/World/

使用例2

let text = " Hello World "

//半角と全角の両方
let result = text.replace(/[  ]/g, "/")

console.log(result);
出力:
/Hello/World/

replaceAll()

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

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

そして、replaceAll()の第1引数に空白の文字列、第2引数に置換後の文字を指定します。

//text=対象の文字列, new=置換後の文字列
let result = text.replaceAll(" ", new)

上記のreplaceAll()は、呼び出した文字列(string)の空白(スペース)を置換した文字列を生成します。

使用例

let text = " Hello World "

let result = text.replaceAll(" ", "/")

console.log(result);
出力:
/Hello/World/

まとめ

文字列(string)の空白(スペース)を置換する方法は、次の2つです。

  • replace()を使う方法
    • let result = text.replace(/ /g, new)
    • let result = text.replace(/[  ]/g, new)
  • replaceAll()を使う方法
    let result = text.replaceAll(" ", new)

コメント

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