fix: 优化 escape 和 unescape 在解析某些特殊字符串时的潜在问题 (#2628)

* fix: 修复 escape 未转义 unicode 中 & 字符的问题

* chore: update

* fix: 优化 unescape 替换顺序,确保为 escape 替换的反向顺序

* chore: update
This commit is contained in:
贤心 2025-04-15 13:23:32 +08:00 committed by GitHub
parent fff6597e10
commit 78438c3429
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 12 additions and 13 deletions

View File

@ -33,7 +33,7 @@
<textarea id="ID-tpl-data">
{
"title": "Layui 常用组件",
"desc": "<a style=\"color:blue;\">一段带 HTML 内容的描述</a>",
"desc": "<a style=\"color:blue;\">一段带 HTML 内容</a>",
"list": [
{
"title": "弹层",

View File

@ -76,9 +76,9 @@
var vars = {
// 字符转义
escape: function(html) {
var exp = /[<"'>]|&(?=#[a-zA-Z0-9]+)/g;
var exp = /[<"'>]|&(?=#?[a-zA-Z0-9]+)/g;
if (html === undefined || html === null) return '';
html = ''+ html;
html += '';
if (!exp.test(html)) return html;
return html.replace(exp, function(str) {
return '&#'+ str.charCodeAt(0) + ';';

View File

@ -348,25 +348,24 @@ layui.define('jquery', function(exports) {
// 转义 html
escape: function(html){
var exp = /[<"'>]|&(?=#[a-zA-Z0-9]+)/g;
var exp = /[<"'>]|&(?=#?[a-zA-Z0-9]+)/g;
if (html === undefined || html === null) return '';
html += '';
if (!exp.test(html)) return html;
return html.replace(/&(?!#?[a-zA-Z0-9]+;)/g, '&amp;')
return html.replace(/&(?=#?[a-zA-Z0-9]+;?)/g, '&amp;')
.replace(/</g, '&lt;').replace(/>/g, '&gt;')
.replace(/'/g, '&#39;').replace(/"/g, '&quot;');
},
// 还原转义的 html
unescape: function(html){
if(html === undefined || html === null) html = '';
html += '';
if (html === undefined || html === null) return '';
return html.replace(/\&amp;/g, '&')
.replace(/\&lt;/g, '<').replace(/\&gt;/g, '>')
.replace(/\&#39;/g, '\'').replace(/\&quot;/g, '"');
return String(html).replace(/\&quot;/g, '"').replace(/\&#39;/g, '\'')
.replace(/\&gt;/g, '>').replace(/\&lt;/g, '<')
.replace(/\&amp;/g, '&');
},
// 打开新窗口