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