使用jQuery轉義HTML字符串

有誰知道一種簡單的方法來從jQuery的字符串中轉義HTML? 我須要可以傳遞任意字符串並正確地對其進行轉義以顯示在HTML頁面中(防止JavaScript / HTML注入攻擊)。 我敢確定能夠擴展jQuery來作到這一點,可是目前我對框架的瞭解還不夠。 html


#1樓

escape()unescape()用於對URL(而非HTML)的字符串進行編碼/解碼。 git

實際上,我使用如下代碼片斷來完成不須要任何框架的技巧: github

var escapedHtml = html.replace(/&/g, '&')
                      .replace(/>/g, '>')
                      .replace(/</g, '&lt;')
                      .replace(/"/g, '&quot;')
                      .replace(/'/g, '&apos;');

#2樓

這是一個乾淨清晰的JavaScript函數。 它將諸如「幾<許多」的文本轉義爲「幾&lt;許多」。 框架

function escapeHtmlEntities (str) {
  if (typeof jQuery !== 'undefined') {
    // Create an empty div to use as a container,
    // then put the raw text in and get the HTML
    // equivalent out.
    return jQuery('<div/>').text(str).html();
  }

  // No jQuery, so use string replace.
  return str
    .replace(/&/g, '&amp;')
    .replace(/>/g, '&gt;')
    .replace(/</g, '&lt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&apos;');
}

#3樓

function htmlEscape(str) {
    var stringval="";
    $.each(str, function (i, element) {
        alert(element);
        stringval += element
            .replace(/&/g, '&amp;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#39;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(' ', '-')
            .replace('?', '-')
            .replace(':', '-')
            .replace('|', '-')
            .replace('.', '-');
    });
    alert(stringval);
    return String(stringval);
}

#4樓

嘗試Underscore.string lib,它與jQuery一塊兒使用。 函數

_.str.escapeHTML('<div>Blah blah blah</div>')

輸出: ui

'&lt;div&gt;Blah blah blah&lt;/div&gt;'

#5樓

mustache.js也提供瞭解決方案 編碼

var entityMap = {
  '&': '&amp;',
  '<': '&lt;',
  '>': '&gt;',
  '"': '&quot;',
  "'": '&#39;',
  '/': '&#x2F;',
  '`': '&#x60;',
  '=': '&#x3D;'
};

function escapeHtml (string) {
  return String(string).replace(/[&<>"'`=\/]/g, function (s) {
    return entityMap[s];
  });
}
相關文章
相關標籤/搜索