Skip to content

Instantly share code, notes, and snippets.

@bannostookaylo
Last active May 4, 2016 16:05
Show Gist options
  • Save bannostookaylo/7c37f023cc8049f19edf496ed956dec4 to your computer and use it in GitHub Desktop.
Save bannostookaylo/7c37f023cc8049f19edf496ed956dec4 to your computer and use it in GitHub Desktop.
function nl2br (str, is_xhtml) {
// * example 1: nl2br('Kevin\nvan\nZonneveld');
// * returns 1: 'Kevin<br />\nvan<br />\nZonneveld'
// * example 2: nl2br("\nOne\nTwo\n\nThree\n", false);
// * returns 2: '<br>\nOne<br>\nTwo<br>\n<br>\nThree<br>\n'
// * example 3: nl2br("\nOne\nTwo\n\nThree\n", true);
// * returns 3: '<br />\nOne<br />\nTwo<br />\n<br />\nThree<br />\n'
var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment