Skip to content

Instantly share code, notes, and snippets.

@RichardDillman
Last active January 31, 2022 18:18
Show Gist options
  • Save RichardDillman/708c81eafa8b922c0214537cb7f24cc9 to your computer and use it in GitHub Desktop.
Save RichardDillman/708c81eafa8b922c0214537cb7f24cc9 to your computer and use it in GitHub Desktop.
General Slugify function. Trim white-space. Replace all non-alphanumeric with dashes. Replace diacritics with generics Reduce chains of dashes to a single dash.
describe("slugify()", () => {
it("Must remove url encodings.", () => {
const result = slugify("New%20York, NY");
expect(result).toBe("new-york-ny");
});
it("Must replace non-alphanumerics with dashes.", () => {
const result = slugify("a@b");
expect(result).toBe("a-b");
});
it("Must trim all whitespace.", () => {
const result = slugify(" ab \r\n");
expect(result).toBe("ab");
});
it("Must never include adjacent dashes.", () => {
const result = slugify("New-York, \nNY");
expect(result).toBe("new-york-ny");
});
it("Must return all alphas as lower case.", () => {
const result = slugify("Amazon, TX");
expect(result).toBe("amazon-tx");
});
it("Must convert diacritics to common characters.", () => {
const result = slugify("Cañon City, Co");
expect(result).toBe("canon-city-co");
});
});
/**
* Convert a string to a slug.
*/
const slugify = (text: string): string => {
const from: string = "àáäâèéëêìíïîòóöôùúüûñç"; // diacritic
const to: string = "aaaaeeeeiiiioooouuuunc"; // generic
let result: string = decodeURIComponent(text) // Remvoe URL encoding
.trim() // remove leading and trailing whitespace
.toLowerCase(); // convert to lower case
from.split("").forEach((x, i) => {
result = result.replace(new RegExp(x, "g"), to.charAt(i)); // replace diacritic
});
result = result
.replace(/[^a-z0-9]/gmi, "-") // replace non-alphanumeric chars with -
.replace(/-+/g, "-"); // collapse dashes
return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment