From 78438c3429bfa88dba42bd260f8859409d9b6621 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=B4=A4=E5=BF=83?= <3277200+sentsim@users.noreply.github.com> Date: Tue, 15 Apr 2025 13:23:32 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E4=BC=98=E5=8C=96=20escape=20=E5=92=8C?= =?UTF-8?q?=20unescape=20=E5=9C=A8=E8=A7=A3=E6=9E=90=E6=9F=90=E4=BA=9B?= =?UTF-8?q?=E7=89=B9=E6=AE=8A=E5=AD=97=E7=AC=A6=E4=B8=B2=E6=97=B6=E7=9A=84?= =?UTF-8?q?=E6=BD=9C=E5=9C=A8=E9=97=AE=E9=A2=98=20(#2628)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix: 修复 escape 未转义 unicode 中 & 字符的问题 * chore: update * fix: 优化 unescape 替换顺序,确保为 escape 替换的反向顺序 * chore: update --- docs/laytpl/detail/demo.md | 2 +- src/modules/laytpl.js | 6 +++--- src/modules/util.js | 17 ++++++++--------- 3 files changed, 12 insertions(+), 13 deletions(-) diff --git a/docs/laytpl/detail/demo.md b/docs/laytpl/detail/demo.md index f0027251..d40a441c 100644 --- a/docs/laytpl/detail/demo.md +++ b/docs/laytpl/detail/demo.md @@ -33,7 +33,7 @@ <textarea id="ID-tpl-data"> { "title": "Layui 常用组件", - "desc": "一段带 HTML 内容的描述", + "desc": "一段带 HTML 的内容", "list": [ { "title": "弹层", diff --git a/src/modules/laytpl.js b/src/modules/laytpl.js index 4dbc29c4..fb6f9131 100644 --- a/src/modules/laytpl.js +++ b/src/modules/laytpl.js @@ -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) + ';'; @@ -472,4 +472,4 @@ }) : global.laytpl = laytpl // 单独引入 ) ); -})(this); \ No newline at end of file +})(this); diff --git a/src/modules/util.js b/src/modules/util.js index a6411746..d258a2e5 100644 --- a/src/modules/util.js +++ b/src/modules/util.js @@ -348,25 +348,24 @@ layui.define('jquery', function(exports) { // 转义 html escape: function(html){ - var exp = /[<"'>]|&(?=#[a-zA-Z0-9]+)/g; - if(html === undefined || html === null) return ''; + var exp = /[<"'>]|&(?=#?[a-zA-Z0-9]+)/g; + if (html === undefined || html === null) return ''; html += ''; - if(!exp.test(html)) return html; + if (!exp.test(html)) return html; - return html.replace(/&(?!#?[a-zA-Z0-9]+;)/g, '&') + return html.replace(/&(?=#?[a-zA-Z0-9]+;?)/g, '&') .replace(//g, '>') .replace(/'/g, ''').replace(/"/g, '"'); }, // 还原转义的 html unescape: function(html){ - if(html === undefined || html === null) html = ''; - html += ''; + if (html === undefined || html === null) return ''; - return html.replace(/\&/g, '&') - .replace(/\</g, '<').replace(/\>/g, '>') - .replace(/\'/g, '\'').replace(/\"/g, '"'); + return String(html).replace(/\"/g, '"').replace(/\'/g, '\'') + .replace(/\>/g, '>').replace(/\</g, '<') + .replace(/\&/g, '&'); }, // 打开新窗口