18
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

innerText(textContent)/innerHTMLを使わずJavaScriptでHTMLエスケープ

Posted at

元になった記事

innerHTMLは"をエスケープしてくれるとは限らない
-- innerText(textContent)/innerHTMLを使ったHTMLエスケープは充分でないので今すぐやめろ、お前たちはもう終わりだ - TODESKING

String#replaceは引数にfunctionを渡せる

functionの第一引数はマッチした部分文字列そのものを保持するので、マッピングテーブルオブジェクトに渡して変換するこんな感じでどうだろう。なんかオシャレな気がするので。

function escapeHtml(content) {
  var TABLE_FOR_ESCAPE_HTML = {
    "&": "&",
    "\"": """,
    "<": "&lt;",
    ">": "&gt;"
  };
  return content.replace(/[&"<>]/g, function(match) {
    return TABLE_FOR_ESCAPE_HTML[match];
  });
}

ブラウザの対応状況とかは調べてないけど、たぶんモダンブラウザなら動くと思う。

参考

ruby/util.rb at trunk · ruby/ruby

18
17
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
18
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?