javaScript nl2br & br2nl functions
The exchange of new line & br HTML tag could refer to PHP - nl2br() function, which uses to inserts HTML line breaks before all newlines in a string. These JavaScript functions consider whether to use insert or replace to handle the swap
nl2br
/**
* This function is same as PHP's nl2br() with default parameters.
*
* @param {string} str Input text
* @param {boolean} replaceMode Use replace instead of insert
* @param {boolean} isXhtml Use XHTML
* @return {string} Filtered text
*/function nl2br (str, replaceMode, isXhtml) {
var breakTag = (isXhtml) ? '<br />' : '<br>';
var replaceStr = (replaceMode) ? '$1'+ breakTag : '$1'+ breakTag +'$2';
return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, replaceStr);}
br2nl
/**
* This function inverses text from PHP's nl2br() with default parameters.
*
* @param {string} str Input text
* @param {boolean} replaceMode Use replace instead of insert
* @return {string} Filtered text
*/function br2nl (str, replaceMode) {
var replaceStr = (replaceMode) ? "\n" : '';
// Includes <br>, <BR>, <br />, </br>
return str.replace(/<\s*\/?br\s*[\/]?>/gi, replaceStr);}
Để lại comment của bạn nếu gặp khó khăn