/** @module entities */
/**
* Encodes HTML entities in a string using the following rules:
*
* - & (ampersand) becomes &
* - " (double quote) becomes "
* - ' (single quote) becomes '
* - < (less than) becomes <
* - > (greater than) becomes >
*
* It is different than dom.encodeHTML, which encodes all characters using the browser's DOMParser. This function only encodes the characters listed above and should be used when DOMParser is not available.
* @see {@link module:dom.encodeHTML}
*
* @param {string} str - The string to encode
* @returns {string} The encoded string
* @example
* htmlEncode('<a href="#">Link</a>') // <a href="#">Link</a>
*/
export function encodeHtmlEntities(str) {
return str.replace(/[<>"'\&]/g, (m) => {
switch (m) {
case '<': return '<'
case '>': return '>'
case '"': return '"'
case "'": return '''
case '&': return '&'
}
})
}
/**
* Decodes HTML entities in a string using the following rules:
*
* - & becomes &
* - " becomes "
* - ' becomes '
* - < becomes <
* - > becomes >
*
* It is different than dom.decodeHTML, which decodes all characters using the browser's DOMParser. This function only decodes the characters listed above and should be used when DOMParser is not available.
* @see {@link module:dom.decodeHTML}
*
* @param {string} str - The string to decode
* @returns {string} The decoded string
* @example
* htmlDecode('<a href="#">Link</a>') // <a href="#">Link</a>
*/
export function decodeHtmlEntities(str) {
return str.replace(/<|>|"|'|&/g, (m) => {
switch (m) {
case '<': return '<'
case '>': return '>'
case '"': return '"'
case ''': return "'"
case '&': return '&'
}
})
}