Skip to content

Commit b3db287

Browse files
Merge pull request #101
Fixed title normalization
2 parents 4cfaefd + 9cbe850 commit b3db287

2 files changed

Lines changed: 45 additions & 3 deletions

File tree

src/utils/strings.ts

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,18 @@
11
import { reservedWords } from "../libs/words";
22

3+
const prepareWords = (value: string): string => {
4+
value = value.replace(/([^\w\d]|[-/_])+/g, " ");
5+
6+
for (const word of reservedWords) {
7+
value = value.replace(
8+
new RegExp(`\\b${word}\\b`, "i"),
9+
word.toLowerCase(),
10+
);
11+
}
12+
13+
return value;
14+
};
15+
316
const normalizeWords = (value: string): string => {
417
for (const word of reservedWords) {
518
value = value.replace(new RegExp(`\\b${word}\\b`, "i"), word);
@@ -13,11 +26,17 @@ export const titleCase = (title?: string) => {
1326
return "";
1427
}
1528

16-
title = title
17-
.replace(/([A-Z])/g, "$1")
29+
const upper: string = title.toUpperCase();
30+
31+
if (upper === title) {
32+
title = title.toLowerCase();
33+
}
34+
35+
title = prepareWords(title)
36+
.replace(/([A-Z])/g, " $1")
1837
.toLowerCase()
1938
.replace(/(^|\s|-|_)\S/g, (match: string) => match.toUpperCase())
20-
.replace(/[-_]/g, " ")
39+
.replace(/(\s|\u3164|\u1160)+/gu, " ")
2140
.trim();
2241

2342
const normalized = normalizeWords(title);

tests/unit/strings.test.ts

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,3 +24,26 @@ test("words", () => {
2424
expect(items.map((item: string) => titleCase(item))).toMatchSnapshot();
2525
}
2626
});
27+
28+
test("case", () => {
29+
expect(titleCase("fooBar")).toBe("Foo Bar");
30+
expect(titleCase("foo Bar")).toBe("Foo Bar");
31+
expect(titleCase("foo bar")).toBe("Foo Bar");
32+
expect(titleCase("FOO BAR")).toBe("Foo Bar");
33+
expect(titleCase("fOo bAr")).toBe("F Oo B Ar");
34+
35+
expect(titleCase("foo-Bar")).toBe("Foo Bar");
36+
expect(titleCase("foo-bar")).toBe("Foo Bar");
37+
expect(titleCase("FOO-BAR")).toBe("Foo Bar");
38+
expect(titleCase("fOo-bAr")).toBe("F Oo B Ar");
39+
40+
expect(titleCase("foo_Bar")).toBe("Foo Bar");
41+
expect(titleCase("foo_bar")).toBe("Foo Bar");
42+
expect(titleCase("FOO_BAR")).toBe("Foo Bar");
43+
expect(titleCase("fOo_bAr")).toBe("F Oo B Ar");
44+
45+
expect(titleCase("foo/Bar")).toBe("Foo Bar");
46+
expect(titleCase("foo/bar")).toBe("Foo Bar");
47+
expect(titleCase("FOO/BAR")).toBe("Foo Bar");
48+
expect(titleCase("fOo/bAr")).toBe("F Oo B Ar");
49+
});

0 commit comments

Comments
 (0)