Skip to content

Instantly share code, notes, and snippets.

@tbjgolden
Created November 8, 2019 17:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tbjgolden/aa26fc09f92c9389b775a843c15ba37d to your computer and use it in GitHub Desktop.
Save tbjgolden/aa26fc09f92c9389b775a843c15ba37d to your computer and use it in GitHub Desktop.
A very short way to safely encode arbitrary data as an id friendly, url safe slug
// For node and pre-babel src
const toSafeSlug = str => "_" + encodeURIComponent(str)
.replace(/[.!~*'()_-]/g, match => `%${match.charCodeAt(0).toString(16)}`.toUpperCase())
.replace(/%/g, "_");
const fromSafeSlug = str => decodeURIComponent(str.substring(1).replace(/_/g, "%"));
// ES5 friendly
function toSafeSlug(str) {
return "_" + encodeURIComponent(str).replace(/[.!~*'()_-]/g, function (match) {
return "%" + (match.charCodeAt(0).toString(16)).toUpperCase();
}).replace(/%/g, "_");
}
function fromSafeSlug(str) {
return decodeURIComponent(str.substring(1).replace(/_/g, "%"));
}
/*
What this does:
const safeSlug = toSafeSlug("%Mega-wow!! hell_yeah 🤣");
<div id={safeSlug} />
// has escaped CSS special chars
document.querySelector(`#${safeSlug}`) matches
// can safely use in a url path without escaping
history.pushState({}, "Mega wow", `/${safeSlug}`);
console.log(fromSafeSlug(safeSlug));
// logs "%Mega-wow!! hell_yeah 🤣"
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment