Skip to content

Commit

Permalink
feat: Slugify utility
Browse files Browse the repository at this point in the history
  • Loading branch information
ChrisGV04 committed Mar 6, 2024
1 parent e7d761a commit 944f37e
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/utils/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export * from './hash';
export * from './slugify';
21 changes: 21 additions & 0 deletions src/utils/slugify.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/**
* Simple utility function to convert any string into an URL-safe version
* @param val Any string
* @returns URL-safe version of the value
*/
export function slugify(val: string): string {
const a = 'àáâäæãåāăąçćčđďèéêëēėęěğǵḧîïíīįìłḿñńǹňôöòóœøōõőṕŕřßśšşșťțûüùúūǘůűųẃẍÿýžźż·/_,:;';
const b = 'aaaaaaaaaacccddeeeeeeeegghiiiiiilmnnnnoooooooooprrsssssttuuuuuuuuuwxyyzzz------';
const p = new RegExp(a.split('').join('|'), 'g');

return val
.toString()
.toLowerCase()
.replace(/\s+/g, '-') // Replace spaces with -
.replace(p, (c) => b.charAt(a.indexOf(c))) // Replace special characters
.replace(/&/g, '-and-') // Replace & with 'and'
.replace(/[^\w\-]+/g, '') // Remove all non-word characters
.replace(/\-\-+/g, '-') // Replace multiple - with single -
.replace(/^-+/, '') // Trim - from start of text
.replace(/-+$/, ''); // Trim - from end of text
}

0 comments on commit 944f37e

Please sign in to comment.