string/escapeHtml.jsjavascript
const entities = { '&': '&', '<': '<', '>': '>', [String.fromCharCode(34)]: '"', [String.fromCharCode(39)]: ''' }
/**
* 转义 HTML 中具有特殊含义的五个字符,不依赖 DOM。
* @function escapeHtml
* @memberof module:string
* @param {string} value 原字符串
* @returns {string} 转义后的字符串
* @throws {TypeError} 参数不是字符串时抛出
*/
function escapeHtml(value) {
if (typeof value !== 'string') throw new TypeError('value must be a string')
return value.replace(/[&<>"']/g, character => entities[character])
}
export default escapeHtml