どうも、ちょげ(@chogetarou)です。
文字列(string)の特定の文字を正規表現で置換する方法を紹介します。
方法

文字列(string)の特定の文字を正規表現で置換するには、replace()を使います。
まず、文字列からreplace()を呼び出します。
そして、replace()の第1引数に置換する文字の正規表現のパターン、第2引数に置換後の文字を指定します。
//text=対象の文字列, pattern=正規表現のパターン, new=置換後の文字列
let result = text.replace(pattern, new)
上記のreplace()は、呼び出した文字列(string)で正規表現のパターンにマッチした文字を置換した文字列を生成します。
使用例
let text = " Hello World "
//空白を置換
let result = text.replace(/\s+/g, "+")
console.log(result);
出力:
+Hello+World+
コメント