PHP's nl2br in TypeScript

✓ Verified: PHP 8.3
Examples tested against actual runtime. CI re-verifies continuously. Only documented examples are tested.

How to use

Install via yarn add locutus and import: import { nl2br } from 'locutus/php/strings/nl2br'.

Or with CommonJS: const { nl2br } = require('locutus/php/strings/nl2br')

Use a bundler that supports tree-shaking so you only ship the functions you actually use. Vite, webpack, Rollup, and Parcel all handle this. For server-side use this is less of a concern.

Examples

These examples are extracted from test cases that automatically verify our functions against their native counterparts.

#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 TypeScript equivalent to PHP's nl2br looks like.

export function nl2br(str: string | null, isXhtml?: boolean): string {
// discuss at: https://locutus.io/php/nl2br/
// parity verified: PHP 8.3
// 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')
}

Improve this function

Locutus is a community effort following The McDonald's Theory: we ship first iterations, hoping others will improve them. If you see something that could be better, we'd love your contribution.

View on GitHub · Edit on GitHub · View Raw


« More PHP strings functions


Star