Skip to content

Commit

Permalink
Merge pull request #1 from nivalis-studio/slugify
Browse files Browse the repository at this point in the history
feat(strings): add slugify fn
  • Loading branch information
pnodet authored Sep 26, 2024
2 parents 996e8f1 + e95c082 commit 4c730b5
Show file tree
Hide file tree
Showing 4 changed files with 49 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,7 @@ export {
truncate,
htmlEscape,
htmlUnescape,
slugify,
} from './strings';

export { parseMs, since, blockTimer } from './time';
Expand Down
1 change: 1 addition & 0 deletions src/strings/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { capitalize } from '..';
export { capitalize, capitalizeWords } from './capitalize';
export { truncate } from './truncate';
export { htmlEscape, htmlUnescape } from './escape';
export { slugify } from './slugify';

/**
* Formats the given string in camel case fashion
Expand Down
24 changes: 24 additions & 0 deletions src/strings/slugify.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { describe, expect, test } from 'bun:test';
import { slugify } from './slugify';

describe('slugify', () => {
test('should return the original string if it is already slug compliant', () => {
expect(slugify('hello')).toBe('hello');
});

test('should replace spaces with hyphens', () => {
expect(slugify('hello world')).toBe('hello-world');
});

test('should remove consecutive hyphens', () => {
expect(slugify('hello world')).toBe('hello-world');
});

test('should remove left and right hyphens', () => {
expect(slugify(' hello world ')).toBe('hello-world');
});

test('should remove accentued and special characters', () => {
expect(slugify("Bonsoir l'Amérique")).toBe('bonsoir-lamerique');
});
});
23 changes: 23 additions & 0 deletions src/strings/slugify.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/**
* Formats the given string in slug url compatible fashion
*
* slugify('hello world') -> 'hello-world'
* slugify('va va_VOOM') -> 'va-va-voom'
* slugify('bonjour l\'Amérique !') -> 'bonjour-lamerique'
* slugify('helloWord 11') -> 'hello-word-11'
* @param {string} str The String to format
* @param text
* @returns {string} The formatted String
*/
export const slugify = (text: string) => {
return text
.normalize('NFD')
.replaceAll(/[\u0300-\u036F]/g, '')
.toLowerCase()
.trim()
.replaceAll(/\s+/g, '-')
.replaceAll(/[^\w-]+/g, '')
.replaceAll(/-{2,}/g, '-')
.replace(/^-+/, '')
.replace(/-+$/, '');
};

0 comments on commit 4c730b5

Please sign in to comment.