PHP's nl2br in JavaScript

How to use

You you can install via yarn add locutus and require this function via const nl2br = require('locutus/php/strings/nl2br').

It is important to use a bundler that supports tree-shaking so that you only ship the functions that you actually use to your browser, instead of all of Locutus, which is massive. Examples are: Parcel, webpack, or rollup.js. For server-side use this is typically less of a concern.

Examples

Please note that these examples are distilled from test cases that automatically verify our functions still work correctly. This could explain some quirky ones.

#codeexpected result
1nl2br('Kevin\nvan\nZonneveld')'Kevin<br />\nvan<br />\nZonneveld'
2nl2br("\nOne\nTwo\n\nThree\n", false)'<br>\nOne<br>\nTwo<br>\n<br>\nThree<br>\n'
3nl2br("\nOne\nTwo\n\nThree\n", true)'<br />\nOne<br />\nTwo<br />\n<br />\nThree<br />\n'
4nl2br(null)''

Here’s what our current JavaScript equivalent to PHP's nl2br looks like.

module.exports = function nl2br(str, isXhtml) {
// discuss at: https://locutus.io/php/nl2br/
// original by: Kevin van Zonneveld (https://kvz.io)
// improved by: Philip Peterson
// improved by: Onno Marsman (https://twitter.com/onnomarsman)
// improved by: Atli Þór
// improved by: Brett Zamir (https://brett-zamir.me)
// improved by: Maximusya
// bugfixed by: Onno Marsman (https://twitter.com/onnomarsman)
// bugfixed by: Kevin van Zonneveld (https://kvz.io)
// bugfixed by: Reynier de la Rosa (https://scriptinside.blogspot.com.es/)
// input by: Brett Zamir (https://brett-zamir.me)
// 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'
// example 4: nl2br(null)
// returns 4: ''

// Some latest browsers when str is null return and unexpected null value
if (typeof str === 'undefined' || str === null) {
return ''
}

// Adjust comment to avoid issue on locutus.io display
const breakTag = isXhtml || typeof isXhtml === 'undefined' ? '<br ' + '/>' : '<br>'

return (str + '').replace(/(\r\n|\n\r|\r|\n)/g, breakTag + '$1')
}

A community effort

Not unlike Wikipedia, Locutus is an ongoing community effort. Our philosophy follows The McDonald’s Theory. This means that we assimilate first iterations with imperfections, hoping for others to take issue with-and improve them. This unorthodox approach has worked very well to foster fun and fruitful collaboration, but please be reminded to use our creations at your own risk. THE SOFTWARE IS PROVIDED "AS IS" has never been more true than for Locutus.

Now go and: [ View on GitHub | Edit on GitHub | View Raw ]


« More PHP strings functions


Star