How can I convert a string to a URL slug in JavaScript?
Richard W
To convert a string to a URL slug in JavaScript, you can follow these steps:
1. Remove leading and trailing spaces from the string using thetrim() method:
1
2
3
4
let string = " This is a sample string ";
string = string.trim();
2. Convert the string to lowercase using thetoLowerCase() method:
1
2
3
string = string.toLowerCase();
3. Replace any special characters, punctuation, or whitespace with dashes using a regular expression and thereplace() method:
By following these steps, the string is transformed into a URL slug suitable for use in URLs, where each word is separated by a dash and all non-alphanumeric characters are removed. You can further modify or extend these steps based on your specific requirements, such as preserving certain special characters or customizing the transformation rules.