This JavaScript function considers whether to use insert or replace to handle the swap.
(Insert or replace HTML line breaks)
/**
* 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);
}