從富文字編輯器獲取html內容組裝json,特殊字元引起報錯解決辦法。
阿新 • • 發佈:2019-02-11
最近專案需要,需要從富文字編輯器獲取html內容組裝json,然後還要
把組裝後的json物件利用json2轉成json字串,資料放入編輯器提交,由於相容ie8以上瀏覽器。所以搞了好久的特殊字元轉義,經常出錯。我們一般想到的解決辦法就是轉義:
/*3.用正則表示式實現html轉碼*/
function htmlEncodeByRegExp(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,""");
s = s.replace(/\n"/g,"");
s = s.replace(/\r"/g,"");
return s;
}
/*4.用正則表示式實現html解碼*/
function htmlDecodeByRegExp (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;
}
json字串本身的引號 和 html裡面的引號,在轉碼後沒法區分哪些是資料格式,哪些屬於從編輯器獲取的Html裡面的。 後來想到一種解決辦法,就是對從富文字編輯器裡面的內容進行base64編碼,展示的時候再解碼,就完全遮蔽掉了所有的特殊字元。 因此採用了jquery.base64.js.具體使用方法是:
編碼
dec.val($.base64.btoa(this.value));
// also possible:
// dec.val( $.base64('encode', this.value) );
// dec.val( $.base64.encode(this.value) );
解碼
// note: you can pass a third parameter to use the utf8 en- / decode option
enc.val($.base64.atob(this.value, true));
// also possible:
// dec.val( $.base64('decode', this.value) );
// dec.val( $.base64.decode(this.value) );