kamaci
kamaci

Reputation: 75117

Replace new line character with <br> tag

I have a string which includes \n inside it. I want to display it as new line in a <div>.

var escapedText = 'Is \n a';
console.log("escapedText: " + escapedText); //it doesn't print \n to console

escapedText.replace(/\\n/g, '<br/>'); 
console.log("escapedText replaced: " + escapedText); //same with above console log

$('#infoText').html(escapedText);

It doesn't work. Any ideas?

Upvotes: 0

Views: 1883

Answers (1)

George
George

Reputation: 36786

  • You don't do anything with escapedText.replace(/\\n/g, '<br/>');. You need to assign it to something.
  • You are escaping the backslash for \n where you shouldn't be.

var escapedText = 'Is \n a';
console.log("escapedText: " + escapedText); //it doesn't print \n to console

escapedText = escapedText.replace(/\n/g, '<br/>'); 
console.log("escapedText replaced: " + escapedText); //same with above console log

$('#infoText').html(escapedText);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="infoText"></div>

Upvotes: 1

Related Questions