Oteto Blogのロゴ

【JavaScript】XSS対策で最低限のサニタイズ(エスケープ)をする

TypeScriptでライブラリを使わずに特殊文字を最低限サニタイズする。

function sanitize(str: string): string {
  return str.replace(/&/g, '&')
    .replace(/'/g, ''')
    .replace(/"/g, '"')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
}

よりシンプルな方法。

const ESCAPE_RULES = {
  '&': '&amp;',
  "'": '&apos;',
  '"': '&quot;',
  '<': '&lt;',
  '>': '&gt;',
};

function sanitize(str: string): string {
  return str.replace(
    /[&'"<>]/g,
    (match) => ESCAPE_RULES[match],
  );
}

対象の特殊文字を列挙しておく方法。こちらの方がスッキリする。