escape text for browser
一、作用
二、为浏览器转义文本
/**
* Escapes text to prevent scripting attacks.
* 转义文本以防止脚本攻击。
*
* @param {*} text Text value to escape.
* 需要转义的文本值
* @return {string} An escaped string.
* 一个转义字符串
*/
function escapeTextForBrowser(text: string | number | boolean): string {
if (
typeof text === 'boolean' ||
typeof text === 'number' ||
typeof text === 'bigint'
) {
// this shortcircuit helps perf for types that we know will never have
// special characters, especially given that this function is used often
// for numeric dom ids.
// 这个短路检查有助于提升性能,适用于我们知道永远不会有特殊字符的类型,尤其是考虑到这个函数
// 经常用于数字 DOM id。
return '' + (text as any);
}
return escapeHtml(text);
}
三、常量
1. 匹配 Html 正则表达式
const matchHtmlRegExp = /["'&<>]/;
四、工具
1. 转义 HTML
备注
checkHtmlStringCoercion()由 CheckStringCoercion#checkHtmlStringCoercion 实现
/**
* Escapes special characters and HTML entities in a given html string.
* * 转义给定 HTML 字符串中的特殊字符和 HTML 实体。
*
* @param {string} string HTML string to escape for later insertion
* @return {string}
* @public
*/
function escapeHtml(string: string) {
if (__DEV__) {
checkHtmlStringCoercion(string);
}
const str = '' + string;
const match = matchHtmlRegExp.exec(str);
if (!match) {
return str;
}
let escape;
let html = '';
let index;
let lastIndex = 0;
for (index = match.index; index < str.length; index++) {
switch (str.charCodeAt(index)) {
case 34: // "
escape = '"';
break;
case 38: // &
escape = '&';
break;
case 39: // '
// 从 escape-html 修改而来;以前是 '''
escape = '''; // modified from escape-html; used to be '''
break;
case 60: // <
escape = '<';
break;
case 62: // >
escape = '>';
break;
default:
continue;
}
if (lastIndex !== index) {
html += str.slice(lastIndex, index);
}
lastIndex = index + 1;
html += escape;
}
return lastIndex !== index ? html + str.slice(lastIndex, index) : html;
}
// end code copied and modified from escape-html
// 结束从 escape-html 复制和修改的代码