Skip to main content

JavaScript function to convert New Line characters to HTML Line Break tags.

/**
 * Convert newline characters to HTML line break tags (ES6+)
 *
 * @param {String} text
 * @param {Boolean} isXhtml Whether or not to self-close the tag.
 * @return {String}
 */
function nl2br(text, isXhtml) {
    const tag = isXhtml || typeof isXhtml === "undefined" ? "<br />" : "<br>";
    return `${text}`.replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, `$1${tag}$2`);
}

/**
 * Convert newline characters to HTML line break tags (ES5)
 *
 * @param {String} text
 * @param {Boolean} isXhtml Whether or not to self-close the tag.
 * @return {String}
 */
function nl2br(text, isXhtml) {
    var tag = isXhtml || typeof isXhtml === "undefined" ? "<br />" : "<br>";
    return ("" + text).replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, "$1" + tag + "$2");
}