PHP's html_entity_decode in JavaScript

How to use

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

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
1html_entity_decode('Kevin & van Zonneveld')'Kevin & van Zonneveld'
2html_entity_decode('<')'<'

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

module.exports = function html_entity_decode(string, quoteStyle) {
// discuss at: https://locutus.io/php/html_entity_decode/
// original by: john (https://www.jd-tech.net)
// input by: ger
// input by: Ratheous
// input by: Nick Kolosov (https://sammy.ru)
// improved by: Kevin van Zonneveld (https://kvz.io)
// improved by: marc andreu
// revised by: Kevin van Zonneveld (https://kvz.io)
// revised by: Kevin van Zonneveld (https://kvz.io)
// bugfixed by: Onno Marsman (https://twitter.com/onnomarsman)
// bugfixed by: Brett Zamir (https://brett-zamir.me)
// bugfixed by: Fox
// example 1: html_entity_decode('Kevin & van Zonneveld')
// returns 1: 'Kevin & van Zonneveld'
// example 2: html_entity_decode('<')
// returns 2: '<'

const getHtmlTranslationTable = require('../strings/get_html_translation_table')
let tmpStr = ''
let entity = ''
let symbol = ''
tmpStr = string.toString()

const hashMap = getHtmlTranslationTable('HTML_ENTITIES', quoteStyle)
if (hashMap === false) {
return false
}

// @todo: & problem
// https://locutus.io/php/get_html_translation_table:416#comment_97660
delete hashMap['&']
hashMap['&'] = '&'

for (symbol in hashMap) {
entity = hashMap[symbol]
tmpStr = tmpStr.split(entity).join(symbol)
}
tmpStr = tmpStr.split(''').join("'")

return tmpStr
}

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