Wednesday, 1 May 2013

Replace new line character to BR tag in JavaScript

function NewLineCharToBR(str, is_xhtml) {
    var RetVal;

    var BreakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';

    RetVal = (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + BreakTag + '$2');

    return RetVal;
}

Ex.
var mystr = "line1\nanother line2\nanother line3";
mystr = NewLineCharToBR (mystr);
alert(mystr);

No comments:

Post a Comment