Dev

By Carlos Santana on
Reading time: 3 minutes

JavaScript-kPdZo.jpg

Normally when we have a textarea and we write some text with break lines, those break lines are saved correctly on the database with the "\n" character, but when you try to render it normally the text is printed in one line instead of adding the break lines.

In PHP exists a function called nl2br to convert the characters to <br /> tags, but how we do this in JavaScript? Well in JavaScript a function like this does not exist natively but I'll show you how you can do it with this function:

function nl2br(str) {
  return str 
    ? str.replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1 <br /> $2')
    : '';
}

nl2br(`My comment with \n breaklines`);

// My comment with <br /> breaklines

If you have any question feel free to add a comment to the post.

avatarLeave a comment

Your comment

Only members can comment. You can Login or Sign Up