Created
July 29, 2024 19:57
-
-
Save kellenmace/43077c7cc5136f54b78749f064e0bccc to your computer and use it in GitHub Desktop.
Generate HTML ID from string
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
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