简体   繁体   中英

Replacing \n or \r\n with <br /> in javascript by using variables

I am passing 2 variables to javascript function,

  1. ReplaceTo = \\n/g

and

  1. ReplaceWith = <br />

Below is the sample input string, desired output and current code I am using, but it does not replace anything.

Input String: Line 1\\nLine 2\\nLine 3\\n

Desired Output String: Line 1<br/>Line 2<br/>Line 3<br/>

var inputStr = "Line 1\nLine 2\nLine 3\n";
var ReplaceTo = "\n/g" ;
var ReplaceWith = "<br />";
inputStr = inputStr.replace(ReplaceTo, ReplaceWith);

I know that if I hard-code in the replace function like .replace(/\\\\n/g, <br />) it will work, but I need to use variables as I am passing values from config.

Can some one please help how to replace using variables with these special characters.

ReplaceTo must be a regex, not an string. Here the working code

 var inputStr = "Line 1\\nLine 2\\nLine 3\\n"; var inputReplace = new RegExp("\\\\n", 'g') var ReplaceWith = "<br />"; inputStr = inputStr.replace(inputReplace, ReplaceWith); console.log(inputStr)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM