Skip to content

Slug

Returns a random slug.

๐ŸŽฌ Usage

<script>
    import {slug} from "@sveu/shared"
</script>
{slug()}

๐Ÿ‘ฉโ€๐Ÿ’ปAPI

๐Ÿ™ˆ Options

Name Description Type Default
lower Use lower letters. boolean True
upper Use uppercase letters. boolean True
digits Use digits. boolean True
size Size of the slug. number 6
prefix Text to use as a prefix. string

โ†ฉ๏ธ Returns

A random slug.

๐Ÿงช Playground

Source Code ๐Ÿ‘€

Source Code
import { range } from "../range"
import type { SlugOptions } from "../utils"

/**
 * Returns a random slug.
 *
 * @param options - The options.
 *
 * @returns A random slug.
 */
export function slug(options: SlugOptions = {}): string {
    const { lower = true, upper = true, digits = true } = options

    let size = options.size || 6

    let chars = ""

    if (size <= 1) size = 2

    if (lower) chars += "abcdefghijklmnopqrstuvwxyz"

    if (upper) chars += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

    if (digits) chars += "0123456789"

    let slug = ""

    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    for (const _ of range(size - 1))
        slug += chars[Math.floor(Math.random() * chars.length)]

    return options.prefix ? `${options.prefix}-${slug}` : slug
}

Last update: 2023-03-07