js 转义
'a/b/c'.replace(/\//g,'\\') // "a\b\c"
$0.value.replace(/\\/g,'\/') // 'a/b/c' 获取到 而不提取出 某个值后进行直接处理
\ 有转义功能,所以一旦解析必然转义,通常是直接获取到数据源进行处理,或者用 input 隐藏赋值后 获取处理、或者正则表达式编解码处理。
扩展一个编解码的函数:
var HtmlUtil = {
htmlEncode: function (html) {
var temp = document.createElement("div");
(temp.textContent != undefined) ? (temp.textContent = html) : (temp.innerText = html);
var output = temp.innerHTML;
temp = null;
return output;
},
htmlDecode: function (text) {
var temp = document.createElement("div");
temp.innerHTML = text;
var output = temp.innerText || temp.textContent;
temp = null;
return output;
},
htmlEncodeByRegExp: function (str) {
var s = "";
if (str.length == 0) return "";
s = str.replace(/&/g, "&");
s = s.replace(/</g, "<");
s = s.replace(/>/g, ">");
s = s.replace(/ /g, " ");
s = s.replace(/\'/g, "'");
s = s.replace(/\"/g, """);
return s;
},
htmlDecodeByRegExp: function (str) {
var s = "";
if (str.length == 0) return "";
s = str.replace(/&/g, "&");
s = s.replace(/</g, "<");
s = s.replace(/>/g, ">");
s = s.replace(/ /g, " ");
s = s.replace(/'/g, "\'");
s = s.replace(/"/g, "\"");
return s;
}
};
// console.log(HtmlUtil.htmlEncode('<input value="E:\\findfile\\b.js" >')); // <input value="E:\findfile\b.js" >
// console.log(HtmlUtil.htmlDecode('<input value="E:\\findfile\\b.js" >')); // <input value="E:\\findfile\\b.js" >
// console.log(HtmlUtil.htmlEncodeByRegExp('<input value="E:\\findfile\\b.js" >')); // <input value="E:\findfile\b.js" >
// console.log(HtmlUtil.htmlDecodeByRegExp('<input value="E:\\findfile\\b.js" >')); //<input value="E:\findfile\b.js" >
3. 单双引号转义
不管是单引号还是双引号,里面都可以套相反的引号,但是要成双成对不可乱套。
在引号里面使用相同的引号,需要用 \ 转义。
代码编译的角度说的话,单引号在JS中被浏览器(IE,Chrome,Safari)编译的速度更快(在FireFox中双引号更快)。
var _html="<div class='content'></div>";
_html='<div class=\'content\'></div>';
4. oth
"123\
456"==='123456' // true
'\8 \09 \189'.length // 8
'\8 \09 \189' // '8 9 89' 无法复制
'\8 \09 \189'.charAt(7) // 9
Put the favorites in the favorites and empty the favorites.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通