js正則還原和轉義特殊字符


還原

function htmlUnEscape(str) {
        return str.replace(/\$#39;|<|>|"|&/g, (match) => {
          switch (match) {
            case '<':
              return '<';
            case '&gt;':
              return '>';
            case '&quot;':
              return '"';
            case '&amp;':
              return '&';
            case "$#39;":
              return '\\';
          }
        });
      }
    let hehe = "&quot;這是&amp;中國&lt;漢字&gt;博大$#39;精深&nbsp;,&copy;&quot;&amp;,&amp;,$#39;  ,','6789',$#39;"
    console.log("----------------",htmlUnEscape(hehe)) //"這是&中國<漢字>博大\精深&nbsp;,&copy;"&,&,\  ,','6789',\

轉義

function htmlEscape(text){ 
        return text.replace(/[<>"&]/g, function(match, pos, originalText){
          switch(match){
          case "<": return "&lt;"; 
          case ">":return "&gt;";
          case "&":return "&amp;"; 
          case "\"":return "&quot;"; 
        } 
        }); 
    }

    let hahah = "<>&\""
    console.log("----------------",htmlEscape(hahah)) ///&lt;&gt;&amp;&quot;

 


免責聲明!

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



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