user3112886
user3112886

Reputation: 21

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.

Upvotes: 1

Views: 194

Answers (1)

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

Related Questions