用于在javascript中转义引号的函数


Function for escaping quotes in javascript?

JavaScript中是否有与PHP中的htmlentities($string, ENT_QUOTES)相同的函数?我搜索了很多,但都找不到,每个人都推荐regex。

在我尝试之前,我只是想确保没有其他更简单的方法

请参阅本教程

它是PHP的htmlentities函数的"端口":

function htmlEntities(str) {
    return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}

好吧,这里有PHP.js的实现:http://phpjs.org/functions/htmlentities/

function htmlentities(string, quote_style, charset, double_encode) {
  //  discuss at: http://phpjs.org/functions/htmlentities/
  // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  //  revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  //  revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // improved by: nobbler
  // improved by: Jack
  // improved by: Rafał Kukawski (http://blog.kukawski.pl)
  // improved by: Dj (http://phpjs.org/functions/htmlentities:425#comment_134018)
  // bugfixed by: Onno Marsman
  // bugfixed by: Brett Zamir (http://brett-zamir.me)
  //    input by: Ratheous
  //  depends on: get_html_translation_table
  //   example 1: htmlentities('Kevin & van Zonneveld');
  //   returns 1: 'Kevin &amp; van Zonneveld'
  //   example 2: htmlentities("foo'bar","ENT_QUOTES");
  //   returns 2: 'foo&#039;bar'
  var hash_map = this.get_html_translation_table('HTML_ENTITIES', quote_style),
    symbol = '';
  string = string == null ? '' : string + '';
  if (!hash_map) {
    return false;
  }
  if (quote_style && quote_style === 'ENT_QUOTES') {
    hash_map["'"] = '&#039;';
  }
  if ( !! double_encode || double_encode == null) {
    for (symbol in hash_map) {
      if (hash_map.hasOwnProperty(symbol)) {
        string = string.split(symbol)
          .join(hash_map[symbol]);
      }
    }
  } else {
    string = string.replace(/(['s'S]*?)(&(?:#'d+|#x['da-f]+|[a-zA-Z]['da-z]*);|$)/g, function(ignore, text, entity) {
      for (symbol in hash_map) {
        if (hash_map.hasOwnProperty(symbol)) {
          text = text.split(symbol)
            .join(hash_map[symbol]);
        }
      }
      return text + entity;
    });
  }
  return string;
}

JavaScript没有任何方便的函数来生成转义HTML。

在JavaScript中为HTML转义数据通常使用DOM方法,并避免将HTML字符串混合在一起。

element.setAttribute("data-foo", 'Example value with a " in it');

在大多数需要将文本转换为HTML字符串的情况下(即,将其放在当前文档中不是最终目标),解决方法是创建一个div元素,然后在其上使用DOM方法,然后读取div的innerHTML属性。

您可能正在寻找此

var encodedStr = rawStr.replace(/['u00A0-'u9999<>'&]/gim, function(i) {
   return '&#'+i.charCodeAt(0)+';';
});

注意,

这段代码将用它们的html实体等价物替换给定范围内的所有字符(unicode 00A0-9999,以及与号,大于和小于),也就是简单的&nnn;其中nnn是我们从charCodeAt获得的unicode值ref