justSmile2

1. JavaScript 特殊字符

2. 正反斜杠互相替换

\'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, "&lt;");
s = s.replace(/>/g, "&gt;");
s = s.replace(/ /g, "&nbsp;");
s = s.replace(/\\'/g, "&#39;");
s = s.replace(/\"/g, "&quot;");
return s;
},
htmlDecodeByRegExp: function (str) {
var s = "";
if (str.length == 0) return "";
s = str.replace(/&amp;/g, "&");
s = s.replace(/&lt;/g, "<");
s = s.replace(/&gt;/g, ">");
s = s.replace(/&nbsp;/g, " ");
s = s.replace(/&#39;/g, "\\'");
s = s.replace(/&quot;/g, "\"");
return s;
}
};
// console.log(HtmlUtil.htmlEncode(\'<input value="E:\\findfile\\b.js" >\')); // &lt;input value="E:\findfile\b.js" &gt;
// console.log(HtmlUtil.htmlDecode(\'&lt;input value="E:\\findfile\\b.js" &gt;\')); // <input value="E:\\findfile\\b.js" >
// console.log(HtmlUtil.htmlEncodeByRegExp(\'<input value="E:\\findfile\\b.js" >\')); // &lt;input&nbsp;value=&quot;E:\findfile\b.js&quot;&nbsp;&gt;
// console.log(HtmlUtil.htmlDecodeByRegExp(\'&lt;input&nbsp;value=&quot;E:\\findfile\\b.js&quot;&nbsp;&gt;\')); //<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

分类:

技术点:

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-08-07
  • 2022-12-23
  • 2021-12-18
  • 2021-12-18
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-12-18
  • 2021-12-18
  • 2021-12-18
  • 2021-12-18
相关资源
相似解决方案