How can I convert a string to a URL slug in JavaScript?
Richard W
richard w profile pic

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:

1
2
3

   string = string.replace(/[\s~`!@#$%^&*()+=,.<>?;:'"[\]{}|\\]/g, '-');
   

4. Remove consecutive dashes and replace them with a single dash using another regular expression and thereplace() method:

1
2
3

   string = string.replace(/-+/g, '-');
   

5. Remove any remaining non-alphanumeric characters using a regular expression and thereplace() method:

1
2
3

   string = string.replace(/[^a-z0-9-]/g, '');
   

6. Return the resulting URL slug:

1
2
3

   console.log(string);  // Output: "this-is-a-sample-string"
   

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.