Friday, 27 June 2014

Convert Newline (\n) to BR tag using javascript/jquery

To maintain textarea's format in the database and display time, we must have to use javascript or jquery's function to detect Enter key of the text area. When user press enter key, text area consider it as the /n instead of the <br> tag. But while displaying it into the HTML, it only understand the <br> tag and remove the /n so format will look like below image's top section. After impelementing the NL to BR replace, it will appear like bottom part of the image.

JS Fiddle Direct Link 

This function remove the NL (\n) and replace it with the BR tag.

function replaceNLtoBR(p_str) 
     return p_str.replace(/(\r\n|\n|\r)/gm,"<br>");
You can also replace BR with NL(\n)

function replaceBRtoNL(p_str) 
     var regex = /<br\s*[\/]?>/gi; 
     return p_str.replace(regex,"\n");
Check this live on the fiddle :

No comments:

Post a Comment