Skip to content

fix: default allowedChars when undefined in slugify - #252

Open
spokodev wants to merge 1 commit into
yf-hk:mainfrom
spokodev:fix/slugify-allowedchars-undefined-default
Open

fix: default allowedChars when undefined in slugify#252
spokodev wants to merge 1 commit into
yf-hk:mainfrom
spokodev:fix/slugify-allowedchars-undefined-default

Conversation

@spokodev

Copy link
Copy Markdown

Problem

slugify() merges options with deepClone({ ...this.options, ...opts }), so an explicitly-passed allowedChars: undefined overrides the default with undefined. That undefined is then interpolated into the character-class template literal as the string "undefined":

slugify('Hello World', { allowedChars: undefined }) // => 'e-d'
slugify('Hello World', { allowedChars: null })      // => 'll-l'

The [^${opt.allowedChars}]+ regex becomes [^undefined]+, so only the letters of the word undefined (u n d e f i) survive — Hello Worlde-d.

This is easy to hit in real code, where options are often spread from optional config:

slugify(title, { separator: '_', allowedChars: cfg.allowedChars /* may be undefined */ });

Fix

The adjacent separator and ignore lookups on the same call already guard against undefined (opt.separator ?? '-', opt.ignore ?? []); allowedChars was simply missing the same fallback. Add it:

new RegExp(`[^${opt.allowedChars ?? defaultOptions.allowedChars}]+`, 'g')

?? covers both undefined and null; an explicit allowedChars: '' is left untouched (still means "allow nothing").

Tests

Added a case next to the existing separator: undefined / ignore: undefined coverage, asserting allowedChars undefined/null falls back to the default. It fails before the change (expected 'e-d' to be 'hello-world') and passes after. Full suite green (86/86), biome check clean.

slugify() merges options with `{ ...this.options, ...opts }`, so passing
`allowedChars: undefined` (e.g. spreading optional config) overrides the
default with `undefined`, which is then coerced into the character-class
template literal as the string "undefined":

  slugify('Hello World', { allowedChars: undefined }) // => 'e-d'

Only the letters of "undefined" survive the `[^undefined]+` filter. The
adjacent `separator` and `ignore` lookups already fall back when undefined
(`?? '-'`, `?? []`); allowedChars was missing the same guard. Add it.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant