[TypeScript]文字列の全ての空白を置換するには?

TypeScript

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

文字列(string)の全ての空白を全て別の文字列に置換する方法を紹介します。

スポンサーリンク

方法

インターフェース, インターネット, プログラム, ブラウザ, Www

文字列(string)の全ての空白を全て別の文字列に置換するには、replace()を使います。

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

そして、replace()の第1引数に「/\s/g」、第2引数に置換後の文字列を指定します。

//new=置換後の文字列
const result: string = text.replace(/\s/g, 'new')

上記のreplace()は、呼び出した文字列(string)の空白を第2引数の文字に置換した文字列を返します。

また、連続した空白をひとまとまりの空白として扱い場合は、replace()の第1引数を「/\s+/g」にします。

const result: string = text.replace(/\s+/g, 'new')

使用例

const text: string = "A B C D E F G H"

const result: string = text.replace(/\s/g, ',')

console.log(result)
出力:
"A,B,C,D,E,F,G,H" 

コメント

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