Creating a slug from a string in JavaScript
Learn how to create URL-friendly slugs from strings in JavaScript, simplifying web development and enhancing SEO.
Creating a slug from a string in JavaScript can be useful for generating URLs or identifiers that are easy to read and share. A slug typically consists of lowercase letters, numbers, hyphens, or underscores, and it does not contain spaces or special characters.
Creating a slug from a string in JavaScript
Here’s how you can create a simple slugifier function in JavaScript:
Code explanation
This JavaScript function, slugify
, is designed to convert a given string (str
) into a URL-friendly format known as a slug
. It does this by replacing characters that aren’t typically allowed in URLs with a specified character or sequence of characters, which by default is a hyphen (-
). The function also allows an optional parameter separator
to specify a different character or sequence to be used instead of the hyphen.
Here’s a breakdown of how it works:
- Input Parameter: the function takes two parameters:
str
: the input string to be converted into a slug.separator
(optional): a character or string to replace hyphens with in the final slug. Defaults to-
.
- Lowercase conversion: the input string is immediately converted to lowercase using
.toLowerCase() method
and then trimmed of leading and trailing whitespace with.trim()
method. This ensures consistency regardless of case or extra spaces. - Character mapping: an array named sets contains objects that map specific sequences of characters (represented as regular expressions) to replacement strings. These mappings cover a wide range of accented letters and special characters, ensuring they are replaced with basic ASCII equivalents or simplified forms. For example, accented vowels like
ÀÁÂÃÄÅ
are mapped to the lettera
, and the sequenceß
is mapped toss
. - Replacement process:
- The
replaceChar
function iterates over each object in the sets array, applying thefrom
toto
mapping to the input string. This is done using theString.prototype.replace
method with a global (g
) and case-insensitive (i
) flag to ensure all instances of the matched characters are replaced. - After processing the
sets
, the function performs several more replacements on the string:- Replaces spaces with hyphens.
- Replaces ampersands (
&
) with-and-
. - Removes all characters that are not alphanumeric or hyphens.
- Ensures there are no double hyphens by replacing them with single hyphens.
- Trims hyphens from both the beginning and end of the string.
- The
- Optional separator replacement: if a separator was provided and it’s not a hyphen, the function replaces all remaining hyphens in the string with the specified separator.
- Return value: finally, the function returns the processed slug as a string.
Example usage
In this example, the original string includes accented characters and punctuation, which are transformed into a URL-friendly slug.
Comments