どうも、ちょげ(@chogetarou)です。
文字列(string)の改行を別の文字に置換する方法を紹介します。
方法

文字列(string)の改行を別の文字に置換するには、replace()を使います。
まず、文字列からreplace()を呼び出します。
そして、replace()の第1引数に「/\n/g
」、第2引数に置換後の文字を指定します。
//text=対象の文字列、new=置換後の文字
let result = text.replace(/\n/g, new)
上記のreplace()は、呼び出した文字列(string)の改行を全て置換した文字列を生成します。
もし、改行にキャリッジリターンを含めたい場合は、第1引数にかリッジリターンを正規表現で指定します。
//キャリッジリターン(\r\n)も置換する
let result = text.replace(/\r?\n/g, new)
使用例
let text = "\nHello\nWorld\n"
let result = text.replace(/\n/g, "/")
console.log(result);
出力:
/Hello/World/
使用例2
let text = "\nHello\r\nWorld\n"
let result = text.replace(/\r?\n/g, "/")
console.log(result);
出力:
/Hello/World/
コメント