Skip to content

Instantly share code, notes, and snippets.

@kellenmace
Created July 29, 2024 19:57
Show Gist options
  • Save kellenmace/43077c7cc5136f54b78749f064e0bccc to your computer and use it in GitHub Desktop.
Save kellenmace/43077c7cc5136f54b78749f064e0bccc to your computer and use it in GitHub Desktop.
Generate HTML ID from string
function generateIdFromString(input) {
return input
.toLowerCase() // Convert the string to lowercase
.replace(/[^a-z0-9\s-]/g, '') // Remove all non-alphanumeric characters except spaces and hyphens
.trim() // Remove leading and trailing spaces
.replace(/\s+/g, '-') // Replace spaces with hyphens
.replace(/-+/g, '-'); // Replace multiple hyphens with a single hyphen
}
// Example usage:
const originalString = "Hello World! This is a Test.";
const idValue = generateIdFromString(originalString);
console.log(idValue); // Output: "hello-world-this-is-a-test"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment