Slugify

slugify(text, maxLength) turns a title like Q3 Invoice — Acme Co. into q3-invoice-acme-co: lowercase letters, numbers, and single hyphens. Use it for file names, URL paths, and IDs that need to be readable and safe everywhere.

When to use

  • Naming Drive files or folders made from sheet rows
  • Building URL paths or query values
  • Making stable, readable IDs or cache keys

How to use this snippet

/** * Turn any text into a lowercase, hyphenated slug. * Accents are stripped, & becomes "and", everything else non-alphanumeric becomes "-". * * @param {*} text * @param {number} [maxLength] optional cap; trailing hyphens are trimmed * @return {string} '' for empty input */ function slugify(text, maxLength) { var s = String(text == null ? '' : text) .normalize('NFKD').replace(/[\u0300-\u036f]/g, '') // strip accents .toLowerCase() .replace(/&/g, ' and ') .replace(/[^a-z0-9]+/g, '-') .replace(/^-+|-+$/g, ''); if (maxLength && s.length > maxLength) s = s.slice(0, maxLength).replace(/-+$/, ''); return s; }

Example

function saveInvoicePdf(title, blob) { var name = slugify(title, 60) + '.pdf'; // "q3-invoice-acme-co.pdf" DriveApp.getFolderById('FOLDER_ID').createFile(blob.setName(name)); }

Notes

  • This is not the same as Sanitize Sheet Name. Tab names can keep spaces and capitals; slugs can't.
  • Two different titles can give the same slug (Acme Co. and ACME co). Add a date or row number if names must be unique.
  • Text with no letters or numbers in it, like —, comes back as ''. Check for that before you use the result.

Happy Coding!

NitroGAS Chrome Extension

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

Get the Extension