summaryrefslogtreecommitdiff
path: root/src-migrate/libs/slug.ts
blob: e8267ed2cb9bdd3811adcc8fe2b268a04399ec03 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import { toTitleCase } from './toTitleCase';

export const createSlug = (
  prefix: string,
  name: string,
  id: string | number,
  withHost: boolean = false
): string => {
  name ||= '';

  // pastikan id jadi string
  const safeId = (id ?? '').toString();

  let slug =
    name
      ?.trim()
      .replace(new RegExp(/[^A-Za-z0-9]/, 'g'), '-') // non alphanumeric -> "-"
      .toLowerCase() +
    '-' +
    safeId;

  const splitSlug = slug.split('-');
  const filterSlugFromEmptyChar = splitSlug.filter((x) => x !== '');
  slug = prefix + filterSlugFromEmptyChar.join('-');

  if (withHost) {
    const host = (process.env.NEXT_PUBLIC_SELF_HOST || '').replace(/\/+$/, '');
    slug = host + slug;
  }

  return slug;
};

export const getIdFromSlug = (slug: string) => {
  let id = slug.split('-');
  return id[id.length - 1];
};

export const getNameFromSlug = (slug: string) => {
  let name = slug.split('-');
  name.pop();
  return toTitleCase(name.join(' '));
};