awesome-string
Version:
The ultimate JavaScript string library
42 lines (39 loc) • 1.39 kB
JavaScript
import coerceToString from 'helper/string/coerce_to_string';
const unescapeCharactersMap = {
'<': /(<)|(�*3c;)|(�*60;)/gi,
'>': /(>)|(�*3e;)|(�*62;)/gi,
'&': /(&)|(�*26;)|(�*38;)/gi,
'"': /(")|(�*22;)|(�*34;)/gi,
"'": /(�*27;)|(�*39;)/gi,
'`': /(�*60;)|(�*96;)/gi
};
const characters = Object.keys(unescapeCharactersMap);
/**
* Replaces the HTML entities with corresponding characters.
*
* @ignore
* @param {string} string The accumulator string.
* @param {string} key The character.
* @return {string} The string with replaced HTML entity
*/
function reduceUnescapedString(string, key) {
return string.replace(unescapeCharactersMap[key], key);
}
/**
* Unescapes HTML special characters from <code>&lt; &gt; &amp; &quot; &#x27; &#x60;</code>
* to corresponding <code>< > & ' " `</code> in <code>subject</code>.
*
* @function unescapeHtml
* @static
* @since 1.0.0
* @memberOf Escape
* @param {string} [subject=''] The string to unescape.
* @return {string} Returns the unescaped string.
* @example
* as.unescapeHtml('<p>wonderful world</p>');
* // => '<p>wonderful world</p>'
*/
export default function unescapeHtml(subject) {
const subjectString = coerceToString(subject);
return characters.reduce(reduceUnescapedString, subjectString);
}