Skip to content

Commit c2f38af

Browse files
committed
feat: add slugify utility and tests
1 parent bda7575 commit c2f38af

3 files changed

Lines changed: 68 additions & 2 deletions

File tree

package/stringUtil/index.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
1-
export { default as escapeHtml } from './escapeHtml';
2-
export { default as unescapeHtml } from './unescapeHtml';
1+
export { default as escapeHtml } from "./escapeHtml";
2+
export { default as unescapeHtml } from "./unescapeHtml";
3+
export { default as slugify } from "./slugify";
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import { describe, expect, test } from "vitest";
2+
import slugify from ".";
3+
4+
describe("slugify", () => {
5+
test("문자열을 slug 형태로 변환한다.", () => {
6+
const input = " Hello World! This is a Test. ";
7+
const output = slugify(input);
8+
expect(output).toBe("hello-world-this-is-a-test");
9+
});
10+
11+
test("특수 문자가 포함된 문자열을 올바르게 변환한다.", () => {
12+
const input = "Café & Restaurant @ Downtown #1";
13+
const output = slugify(input);
14+
expect(output).toBe("caf-restaurant-downtown-1");
15+
});
16+
17+
test("여러 공백과 대시가 포함된 문자열을 올바르게 변환한다.", () => {
18+
const input = "This is---a test---string";
19+
const output = slugify(input);
20+
expect(output).toBe("this-is-a-test-string");
21+
});
22+
23+
test("빈 문자열을 처리한다.", () => {
24+
expect(slugify("")).toBe("");
25+
expect(slugify(" ")).toBe("");
26+
});
27+
28+
test("숫자가 포함된 문자열을 올바르게 변환한다.", () => {
29+
const input = "Product 123 - Version 2.0";
30+
const output = slugify(input);
31+
expect(output).toBe("product-123-version-20");
32+
});
33+
34+
test("특수 문자만 있는 경우를 처리한다.", () => {
35+
const input = "!@#$%^&*()";
36+
const output = slugify(input);
37+
expect(output).toBe("");
38+
});
39+
40+
test("한글이 포함된 문자열을 처리한다.", () => {
41+
expect(slugify("안녕하세요")).toBe("안녕하세요");
42+
expect(slugify("한글 테스트")).toBe("한글-테스트");
43+
expect(slugify("안녕하세요 Hello World")).toBe("안녕하세요-hello-world");
44+
expect(slugify("프로젝트 개발")).toBe("프로젝트-개발");
45+
});
46+
});
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
/**
2+
* 문자열을 URL 친화적인 slug 형태로 변환합니다.
3+
* 공백을 대시(-)로 변환하고, 특수문자를 제거하며, 소문자로 변환합니다.
4+
* 한글도 지원합니다.
5+
*
6+
* @param text - slug로 변환할 문자열
7+
* @returns URL 친화적인 slug 문자열
8+
*/
9+
export default function slugify(text: string): string {
10+
return text
11+
.toString()
12+
.trim()
13+
.toLowerCase()
14+
.replace(/\s+/g, "-")
15+
.replace(/[^a-zA-Z0-9-\-]+/g, "")
16+
.replace(/\-\-+/g, "-")
17+
.replace(/^-+/, "")
18+
.replace(/-+$/, "");
19+
}

0 commit comments

Comments
 (0)