Skip to content

slugifyString() Helper Method

The slugifyString() Helper Method module provides a helper function that takes a string argument and modifies/returns it as a URL safe and human-readable "slug" string.

Import

To import the slugifyString() Helper Method:

javascript
import { slugifyString } from '@obewds/vueventus'

Arguments

Returns: String

ArgsTypeStatusDescription
textStringRequiredString to turn into a slug (URL safe) string
separatorStringOptionalString to use as the separator for the returned slug string

Use Example

javascript
console.log( slugifyString('This is a test.') )
// returns (string): 'this-is-a-test'

console.log( slugifyString(' This is a 2nd test!!!') )
// returns (string): 'this-is-a-2nd-test'

console.log( slugifyString('And (&) THIS is a 3rd?!?!') )
// returns (string): 'and-this-is-a-3rd'

Module Code

ts
// ./src/helpers/slugifyString.ts
// https://gist.github.com/codeguy/6684588#gistcomment-3243980

export default function (text: string, separator: string = '-'): string {

    let txt = text ? text : ''
    let sep = separator ? separator : '-'

    return (txt)
        .toString()
        .toLowerCase()
        .normalize('NFD')
        .trim()
        .replace(/\s+/g, sep)
        .replace(/[^\w\-]+/g, '')
        .replace(/\-\-+/g, sep)
        
}

Released under the MIT License