Escape HTML for HtmlService

Stuffing sheet values straight into HtmlService HTML is how < in a client name breaks the sidebar — or worse, opens an XSS footgun. escapeHtml encodes & < > " ' so status text and labels stay text. Use it before any user/sheet-sourced string hits a template.

What you'll need

  • Strings from sheets, forms, or APIs that will land in HTML
  • An HtmlService sidebar, dialog, or email HTML body

How to use this snippet

function escapeHtml(s) { return String(s == null ? '' : s) .replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/"/g, '&quot;') .replace(/'/g, '&#39;'); } function statusHtml(message) { return '<p class="status">' + escapeHtml(message) + '</p>'; } // In a template: <?= escapeHtml(row.Name) ?> (or pass already-escaped from .gs)

Tips

  • Escape before wrap in tags; never escape a full HTML blob you intend to render as markup.
  • Attribute contexts need the same escapes (especially quotes).
  • Pairs with includeHtml / a tiny sidebar pattern for teammate-facing UIs.

If you're building a fuller sidebar and want help with the HTML/CSS polish, NitroGAS Co-Pilot is optional when a paste isn't enough. Happy Coding.

NitroGAS Chrome Extension

Want this snippet handy inside the Apps Script editor? NitroGAS gives you free themes and snippets — plus optional Co-Pilot when you want a boost (1-week, 1-month, or yearly passes — no subscription). Happy Coding!

Get the Extension