js 轉義


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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM