Skip to content

Commit

Permalink
Add delimiter parameter
Browse files Browse the repository at this point in the history
  • Loading branch information
martpie committed Mar 15, 2019
1 parent 40b7e94 commit b34206b
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 11 deletions.
18 changes: 17 additions & 1 deletion src/__tests__/slugify.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,22 @@ describe ('slugify', () => {
<span>here</span>,
<span>are</span>,
<span>multiple spans</span>,
])).toBe('here-are-multiple-spans');
], '-')).toBe('here-are-multiple-spans');
});

it ('should handle custom delimiters correctly', () => {
expect (slugify('crème brulée', '_')).toBe('creme_brulee');

expect(slugify(<>this IS a NoDe</>, '.')).toBe('this.is.a.node');
});

it ('should handle custom delimiters composed of multiple caracters', () => {
expect(slugify([
<span>here</span>,
<span>are</span>,
<span>multiple spans</span>,
], '--')).toBe('here--are--multiple--spans');

expect(slugify(<span>this IS a NoDe</span>, '__')).toBe('this__is__a__node');
});
});
20 changes: 11 additions & 9 deletions src/slugify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,22 +10,24 @@ const stripAccents = (str: string): string => {
return fixes[accents.indexOf(a)] || '';
}

return str.replace(reg, replacement).toLowerCase();
return str.replace(reg, replacement);
};

const harmonize = (text: string): string => stripAccents(text)
.toLowerCase()
.replace(/\s+/g, '-')
.replace(/[^a-z-]/g, '');
const harmonize = (text: string, delimiter: string): string => {
return stripAccents(text)
.toLowerCase()
.replace(/\s+/g, delimiter)
.replace(new RegExp(`/[^a-z${delimiter}]/g`), '');
};

const slugify = (node: React.ReactNode): string => {
const slugify = (node: React.ReactNode, delimiter = '-'): string => {
// undefined, null, boolean
if (!node || typeof node === 'boolean') {
return '';
}

// string, number
if (typeof node === 'string') return harmonize(node);
if (typeof node === 'string') return harmonize(node, delimiter);
if (typeof node === 'number') return String(node);

// empty object
Expand All @@ -43,12 +45,12 @@ const slugify = (node: React.ReactNode): string => {

// ReactNodeArray
if (node instanceof Array) {
return node.map(n => slugify(n)).join('-');
return node.map(n => slugify(n, delimiter)).join(delimiter);
}


// ReactElement
if ('type' in node) return slugify(node.props.children);
if ('type' in node) return slugify(node.props.children, delimiter);

// unhandled case
return '';
Expand Down
3 changes: 2 additions & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@
"outDir": "dist",
"declaration": true,
"lib": [
"es2017"
"es2017",
"dom"
]
},
"exclude": [
Expand Down

0 comments on commit b34206b

Please sign in to comment.