由於後端返回的html代碼中所有標簽前後都有反斜杠“\”,且有\uxxxx形式的十六進位unicode編碼,如果直接把所有反斜杠替換為%,則會把標簽前後的反斜杠一併替換,導致最後無法轉義,所以先把十六進位開頭的\u替換為%u,則可以使用unescape轉碼,然後再單獨把反斜杠替換為空返回即可。這裡使 ...
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <style> .container{ padding:30px 60px; } .wrap{ padding:10px 0; } .textarea{ width: 98%; border: 1px solid #dcdee2; height: 320px; resize: vertical; text-shadow: 0 1px 0 rgba(255,255,255,.5); -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; padding: 5px 10px; margin-bottom:10px; } .btn{ display: inline-block; margin-bottom: 0; font-weight: 400; text-align: center; -ms-touch-action: manipulation; touch-action: manipulation; cursor: pointer; background-image: none; border: 1px solid transparent; white-space: nowrap; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; padding: 5px 15px 6px; font-size: 12px; border-radius: 4px; transition: color .2s linear,background-color .2s linear,border .2s linear,box-shadow .2s linear; color: #515a6e; background-color: #fff; border-color: #dcdee2; } .btn-primary { color: #fff; background-color: #2d8cf0; border-color: #2d8cf0; font-size: 15px; margin-bottom:20px; } .btn-primary:hover { color: #fff; background-color: #57a3f3; border-color: #57a3f3; } .btn:focus { outline: 0; } </style> </head> <body> <div class="container"> <h1>線上轉義html代碼</h1> <p>粘貼代碼(unicode十六進位代碼)</p> <div> <textarea name="" class="textarea" id="response-html" placeholder="粘貼response填充代碼,形如:\u003c!doctype html\u003e \u003chtml\u003e \u003chead\u003e \u003ctitle\u003eMintegral Interactive Ad\u003c/title\u003e \u003clink href=https://cdn.bootcss.com/Swiper/4.3.2/css/swiper.min.css rel=stylesheet\u003e \u003cmeta name=viewport content=\"initial-scale=1,maximum-scale=1,user-scalable=no\"/\u003e \u003cmeta name=author content=Mintegral\u003e \u003cmeta http-equiv=Content-Type content=\"text/html; charset=utf-8\"\u003e \u003cstyle\u003eg/1.jpg)\u003e \u003cdiv class=obg\u003e\u003c/div\u003e \u003ca …………"></textarea> <button class="btn btn-primary" type="button" id="btn-transfer">轉義</button> <textarea name="" class="textarea" id="transfer-html"></textarea> </div> </div> <script> //轉義html代碼 function decodeUnicode(str) { //先把十六進位unicode編碼/u替換為%u str = str.replace(/\\u/gi,'%u'); //再把頁面中反斜杠替換為空 str = str.replace(/\\/gi,''); return unescape(str); } let btn=document.getElementById("btn-transfer"); let responseHtml=document.getElementById("response-html"); let transferHtml=document.getElementById("transfer-html"); btn.onclick=function () { //獲取當前轉義前html let html=responseHtml.value; //輸出轉義後html transferHtml.value=decodeUnicode(html); } </script> </body> </html>
由於後端返回的html代碼中所有標簽前後都有反斜杠“\”,且有\uxxxx形式的十六進位unicode編碼,如果直接把所有反斜杠替換為%,則會把標簽前後的反斜杠一併替換,導致最後無法轉義,所以先把十六進位開頭的\u替換為%u,則可以使用unescape轉碼,然後再單獨把反斜杠替換為空返回即可。這裡使用decodeURI或者decodeURIComponent方法會報錯,應該代碼格式不對。