Reputation: 21
I am passing 2 variables to javascript function,
\n/g
and
<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.
Upvotes: 1
Views: 194
Reputation: 7923
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)
Upvotes: 1