How can I convert a string to a URL-friendly slug in JavaScript?
Alex K
alex k profile pic

To convert a string to a URL-friendly slug in JavaScript, you can follow these steps: 1. Remove leading and trailing whitespace: Use thetrim() method to eliminate any leading or trailing whitespace in the string. 2. Convert to lowercase: Use thetoLowerCase() method to convert the string to lowercase. This ensures consistent casing in the resulting slug. 3. Replace non-alphanumeric characters with a separator: Use regular expressions and thereplace() method to replace non-alphanumeric characters with a separator, such as a hyphen or underscore. For example, you can use the following regular expression:/[^a-z0-9]+/g. 4. Remove consecutive separators: Use regular expressions and thereplace() method to remove consecutive occurrences of the separator to avoid multiple consecutive separators in the resulting slug. For example, you can use the following regular expression:/[-_]{2,}/g. 5. Trim trailing separators: Use regular expressions and thereplace() method to remove any trailing separators from the slug. For example, you can use the following regular expression:/-|_$/g. 6. Return the final slug: Return the resulting slug string. Here's an example function that implements the steps mentioned above:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

function createSlug(str, separator = '-') {
  const slug = str
    .trim()
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, separator)
    .replace(/[-_]{2,}/g, separator)
    .replace(/-|_$/g, '');

  return slug;
}

// Usage example:
const title = "This is an Example Title!";
const slug = createSlug(title);
console.log(slug); // Output: "this-is-an-example-title"

In the example above, thecreateSlug() function takes a stringstr as input and an optionalseparator parameter (defaulting to a hyphen). It performs the necessary string manipulations to create a URL-friendly slug. The resulting slug is then returned. The function converts the input string to lowercase, replaces non-alphanumeric characters with the separator, removes consecutive separators, and trims trailing separators. The resulting slug is returned as the final output. You can adjust the separator character or modify the regular expressions to match your specific requirements.