js习题(将html中的特殊字符转义和还原)

//定义一个转换html转义特殊字符的方法
function htmlEscape(htmlStr) {
    
    
  return htmlStr.replace(/[<>|"&]/g, (match) => {
    
    
    switch (match) {
    
    
      case '<':
        return '&lt;';
      case '>':
        return '&gt;';
      case '"':
        return '&quot;';
      case '&':
        return '&amp;';
    }
  });
}

//定义一个转换htmlh还原特殊字符的方法
function htmlUnEscape(str) {
    
    
  return str.replace(/&lt;|&gt;|&quot;|&amp;/g, (match) => {
    
    
    switch (match) {
    
    
      case '&lt;':
        return '<';
      case '&gt;':
        return '>';
      case '&quot;':
        return '"';
      case '&amp;':
        return '&';
    }
  });
}

猜你喜欢

转载自blog.csdn.net/weixin_46611729/article/details/109553438