0

I have following jQuery with \n to be replaced with <br /> tag.

var msg = JSON.parse(ev.data)
var test = msg.message;
test.replace(/\n/, "<br />");
//OR
test.replace(/\n/g, "<br />");
//OR
test.replace(/\\n/g, "<br />");

alert(test);

I am unable to get linebreak. I tried all of them but failed. I think string test is not going through replace function.

Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
tashi
  • 249
  • 1
  • 3
  • 16

2 Answers2

1

You need to assign the return value to the variable, replace() will not update the variable

var test = "good\nmorning";
test = test.replace(/\n/g, "<br />");
//--^^^----- update variable `test` with returned value
alert(test);
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
1

except last one, all of them working.

    var test = "good\nmorning";
    test1  = test.replace(/\n/, "<br />");

    console.log(test1);
    //OR
    test2 = test.replace(/\n/g, "<br />");
     console.log(test2);    
    //OR
    test3  = test.replace(/\\n/g, "<br />");
    console.log(test3);
    
Omidam81
  • 1,887
  • 12
  • 20