Skip to content

Commit 01e4afa

Browse files
committed
feat: added generateSlug util
1 parent 42d141a commit 01e4afa

File tree

3 files changed

+34
-0
lines changed

3 files changed

+34
-0
lines changed

src/__tests__/generateSlug.test.ts

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import { generateSlug } from "../generateSlug";
2+
3+
describe("generateSlug", () => {
4+
it("should convert string to lowercase and replace spaces with hyphens", () => {
5+
expect(generateSlug("Hello World")).toBe("hello-world");
6+
});
7+
8+
it("should remove special characters and trim hyphens", () => {
9+
expect(generateSlug(" Hello @#$ World! ")).toBe("hello-world");
10+
});
11+
12+
it("should handle multiple consecutive non-alphanumerics", () => {
13+
expect(generateSlug("This---is_a_test")).toBe("this-is-a-test");
14+
});
15+
16+
it("should return empty string for input with only non-alphanumerics", () => {
17+
expect(generateSlug("!!!")).toBe("");
18+
});
19+
20+
it("should preserve numbers in the slug", () => {
21+
expect(generateSlug("Product 123")).toBe("product-123");
22+
});
23+
24+
it("should handle already well-formatted slug", () => {
25+
expect(generateSlug("already-slugified")).toBe("already-slugified");
26+
});
27+
});

src/generateSlug.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
export const generateSlug = (str: string): string => {
2+
return str
3+
.toLowerCase()
4+
.replace(/[^a-z0-9]+/g, "-")
5+
.replace(/(^-|-$)/g, "");
6+
};

src/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ export { camelToSentenceCase } from "./camelToSentenceCase";
22
export { coercedGet } from "./coercedGet";
33
export { extractLatLngFromGoogleMapsUrl } from "./extractLatLngFromGoogleMapsUrl";
44
export { generatePrefixedId } from "./generatePrefixedId";
5+
export { generateSlug } from "./generateSlug";
56
export { isValidEmail } from "./isValidEmail";
67
export { isValidGoogleMapsUrl } from "./isValidGoogleMapsUrl";
78
export { isValidHttpUrl } from "./isValidHttpUrl";

0 commit comments

Comments
 (0)