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;

 

posted @ 2021-01-04 14:08  煎饼不要香菜呀  阅读(1838)  评论(0编辑  收藏  举报