Created
November 8, 2019 17:12
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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