im-ui-mobile
Version:
A Vue3.0 + Typescript instant messaging component library for Uniapp
148 lines (128 loc) • 3.25 kB
JavaScript
// HTML 转义工具函数
/**
* HTML 特殊字符转义映射
*/
const HTML_ESCAPE_MAP = {
'<': '<',
'>': '>',
'&': '&',
'"': '"',
"'": ''',
'`': '`'
};
/**
* 反转的 HTML 转义映射(用于反转义)
*/
const HTML_UNESCAPE_MAP = {
'<': '<',
'>': '>',
'&': '&',
'"': '"',
''': "'",
'`': '`'
};
/**
* 将 HTML 特殊字符转义为实体
* @param {string} text - 原始文本
* @returns {string} 转义后的文本
*/
const html2Escape = (text) => {
if (!text) return '';
return text.replace(/[<>&"']/g, (char) => {
return HTML_ESCAPE_MAP[char] || char;
});
};
/**
* 更全面的 HTML 转义函数(包含更多特殊字符)
* @param {string} text - 原始文本
* @returns {string} 转义后的文本
*/
const htmlEscape = (text) => {
if (!text) return '';
const escapeRegex = /[<>&"'`]/g;
return text.replace(escapeRegex, (char) => {
return HTML_ESCAPE_MAP[char] || char;
});
};
/**
* 将 HTML 实体反转义为特殊字符
* @param {string} text - 转义后的文本
* @returns {string} 原始文本
*/
const htmlUnescape = (text) => {
if (!text) return '';
const unescapeRegex = /&(lt|gt|amp|quot|#39|#96);/g;
return text.replace(unescapeRegex, (entity) => {
return HTML_UNESCAPE_MAP[entity] || entity;
});
};
/**
* 转义 HTML 属性值
* @param {string} value - 属性值
* @returns {string} 转义后的属性值
*/
const escapeAttribute = (value) => {
if (!value) return '';
return value
.replace(/"/g, '"')
.replace(/'/g, ''')
.replace(/</g, '<')
.replace(/>/g, '>');
};
/**
* 转义 HTML 文本内容(不转义单引号)
* @param {string} text - 文本内容
* @returns {string} 转义后的文本内容
*/
const escapeTextContent = (text) => {
if (!text) return '';
return text
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"');
};
/**
* 检查文本是否包含需要转义的 HTML 特殊字符
* @param {string} text - 要检查的文本
* @returns {boolean} 是否包含特殊字符
*/
const hasHtmlSpecialChars = (text) => {
if (!text) return false;
return /[<>&"']/.test(text);
};
/**
* 安全的设置 innerHTML(自动转义)
* @param {HTMLElement} element - DOM 元素
* @param {string} html - HTML 内容
*/
const setSafeHTML = (element, html) => {
if (!element) return;
element.innerHTML = htmlEscape(html);
};
/**
* 安全的创建 HTML 字符串
* @param {TemplateStringsArray} strings - 模板字符串数组
* @param {...any} values - 插入值数组
* @returns {string} 安全的 HTML 字符串
*/
const safeHTML = (strings, ...values) => {
let result = '';
for (let i = 0; i < strings.length; i++) {
result += strings[i];
if (i < values.length) {
result += htmlEscape(String(values[i]));
}
}
return result;
};
export default {
html2Escape,
htmlEscape,
htmlUnescape,
escapeAttribute,
escapeTextContent,
hasHtmlSpecialChars,
setSafeHTML,
safeHTML
};