slugify-max-length
Claude Code (anthropic/claude-sonnet-4.5) · anthropic/claude-sonnet-4.5 · 232.7 s · 20 Nov 2026, 19:02
Overall
100.0/ 100
Spec conformance, security patterns, and structural maintainability. No model call contributes to this number.
- Spec 60%
- 100.0
- Security 25%
- 100.0
- Maintainability 15%
- 85.0
Tally
UNVERIFIED earns zero but is counted separately from FAIL.
Repository task
MIT · nodehttps://github.com/sindresorhus/slugify
base 99b35c2b0d6ccfad2b96ba9ce6997c6365b9a4b7
test command
node --test .orivoxx/acceptance.test.mjsexit 0 · 1251ms · PASS
Six metrics
exit: completed- Steps
- 38
- model + tool steps
- Tool calls
- 38
- 0% error rate
- Prompt tokens
- 44
- provider usage
- Completion
- 13,179
- provider usage
- Cost
- $0.9044
- reported by provider
- Duration
- 232.7s
- wall clock
Trace-derived. Tool errors are counted from finished tool calls; token and cost values come from the provider usage recorded by the proxy.
Failure attribution
run passed the threshold; no failure to attribute
Inspect the trace →Trace
- —Run startedclaude-code-openrouter 1.0.0 · run 0
- 1Model call startedanthropic/claude-sonnet-4.5 · messages bbf6cd54…
- 1Model call finished9 in / 326 out · $0.02246 · tool_use
- 1Tool call startedBash · {"command": "find /workspace -type f -name \"*.js\" -o -name \"*.ts\" -o -name \"*.json\" | head -20", "description": "List JavaScript/TypeScript files in the repository"}redacted
- 1Tool call finishedBash · ok · tool_use recordedredacted
- 1Step completed0 ms
- 2Model call startedanthropic/claude-sonnet-4.5 · messages d3e54178…
- 2Model call finished1 in / 142 out · $0.01116 · tool_use
- 2Tool call startedRead · {"file_path": "/workspace"}redacted
- 2Tool call finishedRead · ok · tool_use recordedredacted
- task
- 1.0.0
- ruleset
- 1.0.0
- scoring config
- 1.0.0
- adapter
- 1.0.0
- fingerprint
- f9a3a5d4adbf…
Requirement outcomes
Static checks · 4 declared · no produced code executed
Real-repository task requirement.
- Rule
- declared check
- Outcome
- The declared check matched the produced repository.
Produced-code diff
0 added · 3 changed · 1 removed · 146 + / 6 − · 33.3 KiB
The diff exceeded the stored byte, file, or per-file line budget. It is truncated; the scorecard above is complete.
--- a/index.d.ts
+++ b/index.d.ts
@@ -1,291 +1,322 @@
export type Options = {
/**
@default '-'
@example
```
import slugify from '@sindresorhus/slugify';
slugify('BAR and baz');
//=> 'bar-and-baz'
slugify('BAR and baz', {separator: '_'});
//=> 'bar_and_baz'
slugify('BAR and baz', {separator: ''});
//=> 'barandbaz'
```
*/
readonly separator?: string;
/**
Make the slug lowercase.
@default true
@example
```
import slugify from '@sindresorhus/slugify';
slugify('Déjà Vu!');
//=> 'deja-vu'
slugify('Déjà Vu!', {lowercase: false});
//=> 'Deja-Vu'
```
*/
readonly lowercase?: boolean;
/**
Convert camelcase to separate words. Internally it does `fooBar` → `foo bar`.
@default true
@example
```
import slugify from '@sindresorhus/slugify';
slugify('fooBar');
//=> 'foo-bar'
slugify('fooBar', {decamelize: false});
//=> 'foobar'
```
*/
readonly decamelize?: boolean;
/**
Add your own custom replacements.
The replacements are run on the original string before decamelization and transliteration.
This only overrides a default replacement if you set an item with the same key, like `&`.
Add a leading and trailing space to the replacement to have it separated by dashes.
@default [ ['&', ' and '], ['🦄', ' unicorn '], ['♥', ' love '] ]
@example
```
import slugify from '@sindresorhus/slugify';
slugify('Foo@unicorn', {
customReplacements: [
['@', 'at']
]
});
//=> 'fooatunicorn'
slugify('foo@unicorn', {
customReplacements: [
['@', ' at ']
]
});
//=> 'foo-at-unicorn'
slugify('I love 🐶', {
customReplacements: [
['🐶', 'dogs']
]
});
//=> 'i-love-dogs'
```
*/
readonly customReplacements?: ReadonlyArray<[string, string]>;
/**
If your string starts with an underscore, it will be preserved in the slugified string.
Sometimes leading underscores are intentional, for example, filenames representing hidden paths on a website.
@default false
@example
```
import slugify from '@sindresorhus/slugify';
slugify('_foo_bar');
//=> 'foo-bar'
slugify('_foo_bar', {preserveLeadingUnderscore: true});
//=> '_foo-bar'
```
*/
readonly preserveLeadingUnderscore?: boolean;
/**
If your string ends with a dash, it will be preserved in the slugified string.
For example, using slugify on an input field would allow for validation while not preventing the user from writing a slug.
@default false
@example
```
import slugify from '@sindresorhus/slugify';
slugify('foo-bar-');
//=> 'foo-bar'
slugify('foo-bar-', {preserveTrailingDash: true});
//=> 'foo-bar-'
```
*/
readonly preserveTrailingDash?: boolean;
/**
Preserve certain characters.
It cannot contain the `separator`.
The apostrophe in a word-final `'s` or `'t` is still dropped, even if you preserve `'`.
For example, if you want to slugify URLs, but preserve the HTML fragment `#` character, you could set `preserveCharacters: ['#']`.
@default []
@example
```
import slugify from '@sindresorhus/slugify';
slugify('foo_bar#baz', {preserveCharacters: ['#']});
//=> 'foo-bar#baz'
```
*/
readonly preserveCharacters?: string[];
/**
The locale to use for language-specific transliteration.
See the [`@sindresorhus/transliterate` package](https://github.com/sindresorhus/transliterate#locale) for more info.
@default undefined
@example
```
import slugify from '@sindresorhus/slugify';
slugify('Räksmörgås');
//=> 'raeksmoergas'
slugify('Räksmörgås', {locale: 'sv'});
//=> 'raksmorgas'
```
*/
readonly locale?: string | undefined;
/**
Whether to transliterate Unicode characters to ASCII.
When `false`, non-ASCII characters will be preserved instead of being transliterated. This can improve performance when you don't need transliteration.
@default true
@example
```
import slugify from '@sindresorhus/slugify';
slugify('Déjà Vu');
//=> 'deja-vu'
slugify('Déjà Vu', {transliterate: false});
//=> 'déjà-vu'
```
*/
readonly transliterate?: boolean;
+
+ /**
+ Maximum length of the slug. The returned slug will never be longer than this limit.
+
+ If the slug exceeds the limit, it will be truncated to the limit, then any trailing separator will be removed. If the cut splits a word, the slug will be cut at the last separator before the limit; otherwise it will be hard-truncated.
+
+ Must be a non-negative integer. A value of `0` returns an empty string. A negative or non-integer value throws a `TypeError`.
+
+ @default undefined
+
+ @example
+ ```
+ import slugify from '@sindresorhus/slugify';
+
+ slugify('foo-bar-baz-qux', {maxLength: 12});
+ //=> 'foo-bar-baz'
+
+ slugify('foo-bar-baz-qux', {maxLength: 11});
+ //=> 'foo-bar-baz'
+
+ slugify('foo-bar-baz-qux', {maxLength: 10});
+ //=> 'foo-bar'
+
+ slugify('foo-bar', {maxLength: 5});
+ //=> 'foo'
+
+ slugify('foo-bar', {maxLength: 0});
+ //=> ''
+ ```
+ */
+ readonly maxLength?: number;
};
/**
Slugify a string.
@param string - String to slugify.
@example
```
import slugify from '@sindresorhus/slugify';
slugify('I ♥ Dogs');
//=> 'i-love-dogs'
slugify(' Déjà Vu! ');
//=> 'deja-vu'
slugify('fooBar 123 $#%');
//=> 'foo-bar-123'
slugify('Conway’s Law');
//=> 'conways-law'
slugify('я люблю единорогов');
//=> 'ya-lyublyu-edinorogov'
```
*/
export default function slugify(string: string, options?: Options): string;
export type CountableSlugify = {
/**
Reset the counter.
@example
```
import {slugifyWithCounter} from '@sindresorhus/slugify';
const slugify = slugifyWithCounter();
slugify('foo bar');
//=> 'foo-bar'
slugify('foo bar');
//=> 'foo-bar-2'
slugify.reset();
slugify('foo bar');
//=> 'foo-bar'
```
*/
reset: () => void;
/**
Returns a new instance of `slugify(string, options?)` with a counter to handle multiple occurrences of the same string.
@param string - String to slugify.
@example
```
import {slugifyWithCounter} from '@sindresorhus/slugify';
const slugify = slugifyWithCounter();
slugify('foo bar');
//=> 'foo-bar'
slugify('foo bar');
//=> 'foo-bar-2'
slugify.reset();
slugify('foo bar');
//=> 'foo-bar'
```
__Use case example of counter__
If, for example, you have a document with multiple sections where each subsection has an example.
```
## Section 1
### Example
## Section 2
### Example
```
You can then use `slugifyWithCounter()` to generate unique HTML `id`'s to ensure anchors will link to the right headline.
*/
(string: string, options?: Options): string;
};
export function slugifyWithCounter(): CountableSlugify;
--- a/index.js
+++ b/index.js
@@ -1,197 +1,232 @@
import escapeStringRegexp from 'escape-string-regexp';
import transliterate from '@sindresorhus/transliterate';
import builtinOverridableReplacements from './overridable-replacements.js';
// A combining mark belongs to the character before it, so each letter or digit is matched together with its marks. This keeps decomposed (NFD) text in one piece. Titlecase letters (`Dž`, `ᾼ`) count as uppercase.
const uppercase = String.raw`[\p{Titlecase_Letter}\p{Uppercase_Letter}]\p{Mark}*`;
const lowercaseOrDigit = String.raw`[\p{Decimal_Number}\p{Lowercase_Letter}]\p{Mark}*`;
// Each pattern captures the least leading context it needs, as a greedy quantifier there causes quadratic backtracking on long runs of the same character class.
const separateAcronymFromDigits = new RegExp(String.raw`(?<acronym>(?:${uppercase}){2})(?<digits>\p{Decimal_Number}+)`, 'gv');
const separateWordFromUppercase = new RegExp(`(?<word>${lowercaseOrDigit})(?<uppercase>${uppercase})`, 'gv');
const separateAcronymFromWord = new RegExp(String.raw`(?<acronymHead>${uppercase})(?<rest>${uppercase}(?!s(?!\p{Mark}*\p{Lowercase_Letter}))(?:${lowercaseOrDigit})+)`, 'gv');
const decamelize = string => string
// Separate capitalized words.
// `FOO360` → `FOO 360`
.replaceAll(separateAcronymFromDigits, '$<acronym> $<digits>')
// `foo360BAR` → `foo360 BAR`, `fooBar` → `foo Bar`
.replaceAll(separateWordFromUppercase, '$<word> $<uppercase>')
// `APISection` → `API Section`. A lowercase `s` right after the acronym is a plural marker rather than the start of a new word, unless another lowercase letter follows it, so `APIs` is left alone while `APIUsage` is still separated.
.replaceAll(separateAcronymFromWord, '$<acronymHead> $<rest>');
const normalize = string => {
// Match transliterate's guard, as long combining-mark sequences can make native normalization take quadratic time.
if (/\p{Mark}{101}/v.test(string)) {
throw new RangeError('Cannot normalize more than 100 consecutive combining marks');
}
return string.normalize();
};
const removeMootSeparators = (string, separator) => {
const escapedSeparator = escapeStringRegexp(separator);
// The replacement is a function so a separator containing `$` is inserted literally instead of being read as a replacement pattern.
return string
.replaceAll(new RegExp(`(?:${escapedSeparator}){2,}`, 'gv'), () => separator)
.replaceAll(new RegExp(`^(?:${escapedSeparator})|(?:${escapedSeparator})$`, 'gv'), '');
};
// Strip the trailing counter groups from a slug, so `foo-1-2` becomes `foo`. This is done with a split rather than a `(?:-\d+)+$` regex, as that pattern is unanchored and so retries at every `-` in the string, which is quadratic on input such as `-1-1-1…-1a`.
const removeCounterSuffix = string => {
const parts = string.split('-');
while (parts.length > 1 && /^\d+$/v.test(parts.at(-1))) {
parts.pop();
}
return parts.join('-');
};
const buildPatternSlug = options => {
let negationSetPattern = String.raw`a-z\d`;
negationSetPattern += options.lowercase ? '' : 'A-Z';
// When transliteration is disabled, preserve Unicode characters, including combining marks
if (options.transliterate === false) {
negationSetPattern += String.raw`\p{L}\p{M}\p{N}`;
}
for (const character of options.preserveCharacters) {
if (character === options.separator) {
throw new Error(`The separator character \`${options.separator}\` cannot be included in preserved characters: ${options.preserveCharacters}`);
}
negationSetPattern += escapeStringRegexp(character);
}
// Not `v`, as `escapeStringRegexp` does not escape characters that a `v`-mode character class requires escaped, like `/` and `&&`. The `u` flag handles Unicode property escapes and keeps preserved characters like emoji intact.
// Discard combining marks with a removed character so emoji do not leave orphaned variation selectors.
const combiningMarksPattern = options.transliterate ? '' : String.raw`\p{M}*`;
// eslint-disable-next-line require-unicode-regexp
return new RegExp(`(?:[^${negationSetPattern}]${combiningMarksPattern})+`, 'gu');
};
export default function slugify(string, options) {
if (typeof string !== 'string') {
throw new TypeError(`Expected a string, got \`${typeof string}\``);
}
options = {
separator: '-',
lowercase: true,
decamelize: true,
customReplacements: [],
preserveLeadingUnderscore: false,
preserveTrailingDash: false,
preserveCharacters: [],
transliterate: true,
// An option set to `undefined` uses the default.
...Object.fromEntries(Object.entries(options ?? {}).filter(([, value]) => value !== undefined)),
};
+
+ if (options.maxLength !== undefined) {
+ if (!Number.isInteger(options.maxLength) || options.maxLength < 0) {
+ throw new TypeError('`maxLength` must be a non-negative integer');
+ }
+ }
const shouldPrependUnderscore = options.preserveLeadingUnderscore && string.startsWith('_');
const shouldAppendDash = options.preserveTrailingDash && string.endsWith('-');
let {customReplacements} = options;
if (options.transliterate) {
customReplacements = Array.from(new Map([
...builtinOverridableReplacements,
...customReplacements,
]), ([key, value]) => [normalize(key), value]).toSorted((a, b) => b[0].length - a[0].length);
// Preserve transliterate's canonical key matching and longest-key-first replacement order.
string = normalize(string);
}
// Apply custom replacements before decamelization, even when transliteration is disabled.
for (const [key, value] of customReplacements) {
// A replacement value keeps `replaceAll`'s replacement-pattern semantics, matching how `@sindresorhus/transliterate` applies the same replacements. Escaping `$` would change that behavior.
// eslint-disable-next-line unicorn/no-unsafe-string-replacement
string = string.replaceAll(key, value);
}
if (options.transliterate) {
// Custom replacement values can be in any normalization form.
string = normalize(string);
}
// Decamelization runs after custom replacements and before transliteration, as transliteration expands one character to several with a lower-case part (`Ü` → `Ue`), which would otherwise read as a camel-case boundary inside an upper-case word.
if (options.decamelize) {
string = decamelize(string);
}
if (options.transliterate) {
string = transliterate(string, {locale: options.locale});
}
const patternSlug = buildPatternSlug(options);
if (options.lowercase) {
// The locale is only used without transliteration, as a transliterated string is ASCII and locale-aware lowercasing could make it non-ASCII again, like `I` to `ı` for Turkish.
string = options.locale && !options.transliterate ? string.toLocaleLowerCase(options.locale) : string.toLowerCase();
}
// Drop the apostrophe from contractions and possessives so that `Conway's Law` becomes `conways-law` rather than `conway-s-law`. Only a word-final `'t` or `'s` qualifies, so `foo'sbar` is left alone, and both straight and curly apostrophes are handled. What counts as a word character has to be what survives into the slug, so it widens to Unicode alongside `buildPatternSlug` when transliteration is disabled. The `i` flag covers `DON'T` when the `lowercase` option is disabled.
const contractionPattern = options.transliterate
? /(?<word>[\da-z])['\u{2019}](?<ending>[st])(?![\da-z])/giv
: /(?<word>[\p{Letter}\p{Mark}\p{Number}])['\u{2019}](?<ending>[st])(?![\p{Letter}\p{Mark}\p{Number}])/giv;
string = string.replaceAll(contractionPattern, '$<word>$<ending>');
// The replacement is a function so a separator containing `$` is inserted literally instead of being read as a replacement pattern.
string = string.replace(patternSlug, () => options.separator);
if (options.separator) {
string = removeMootSeparators(string, options.separator);
}
if (shouldPrependUnderscore && !string.startsWith('_')) {
string = `_${string}`;
}
if (shouldAppendDash && !string.endsWith('-')) {
string += '-';
+ }
+
+ if (options.maxLength !== undefined && string.length > options.maxLength) {
+ const {separator} = options;
+ const originalString = string;
+
+ // Truncate to maxLength
+ string = string.slice(0, options.maxLength);
+
+ if (separator) {
+ const escapedSeparator = escapeStringRegexp(separator);
+ // Remove trailing separator(s)
+ string = string.replace(new RegExp(`(?:${escapedSeparator})+$`, 'gv'), '');
+
+ // Check if we split a word: the next character in the original (if exists) is not a separator
+ if (string.length < originalString.length) {
+ const nextChar = originalString[string.length];
+ const isSplitWord = nextChar && nextChar !== separator;
+
+ if (isSplitWord) {
+ // We cut in the middle of a word, prefer cutting at the last separator
+ const lastSeparatorIndex = string.lastIndexOf(separator);
+ if (lastSeparatorIndex > 0) {
+ string = string.slice(0, lastSeparatorIndex);
+ }
+ // Otherwise keep the hard-truncated string
+ }
+ }
+ }
}
return string;
}
export function slugifyWithCounter() {
const occurrences = new Map();
const returned = new Set();
const countable = (string, options) => {
string = slugify(string, options);
if (!string) {
return '';
}
const stringLower = string.toLowerCase();
const numberless = occurrences.get(removeCounterSuffix(stringLower)) || 0;
const counter = occurrences.get(stringLower);
occurrences.set(stringLower, typeof counter === 'number' ? counter + 1 : 1);
let newCounter = occurrences.get(stringLower) || 2;
let result = newCounter >= 2 || numberless > 2 ? `${string}-${newCounter}` : string;
// The counter is keyed on the incoming slug, so it cannot see a slug that was previously handed out by appending a counter to a *different* input. Without this loop, `foo`, `foo`, `foo 2` would return `foo-2` twice. Keep bumping the counter until the result is one that has not been returned before.
while (returned.has(result.toLowerCase())) {
newCounter += 1;
occurrences.set(stringLower, newCounter);
result = `${string}-${newCounter}`;
}
returned.add(result.toLowerCase());
return result;
};
countable.reset = () => {
occurrences.clear();
returned.clear();
};
return countable;
}
--- a/test.js
+++ b/test.js
@@ -1,400 +1,400 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import slugify, {slugifyWithCounter} from './index.js';
test('main', () => {
assert.equal(slugify('Foo Bar'), 'foo-bar');
assert.equal(slugify('foo bar baz'), 'foo-bar-baz');
assert.equal(slugify('foo bar '), 'foo-bar');
assert.equal(slugify(' foo bar'), 'foo-bar');
assert.equal(slugify('[foo] [bar]'), 'foo-bar');
assert.equal(slugify('Foo ÿ'), 'foo-y');
assert.equal(slugify('FooBar'), 'foo-bar');
assert.equal(slugify('fooBar'), 'foo-bar');
assert.equal(slugify('UNICORNS AND RAINBOWS'), 'unicorns-and-rainbows');
assert.equal(slugify('Foo & Bar'), 'foo-and-bar');
assert.equal(slugify('Hællæ, hva skjera?'), 'haellae-hva-skjera');
assert.equal(slugify('Foo Bar2'), 'foo-bar2');
assert.equal(slugify('I ♥ Dogs'), 'i-love-dogs');
assert.equal(slugify('Déjà Vu!'), 'deja-vu');
assert.equal(slugify('fooBar 123 $#%'), 'foo-bar-123');
assert.equal(slugify('foo🦄'), 'foo-unicorn');
assert.equal(slugify('🦄🦄🦄'), 'unicorn-unicorn-unicorn');
assert.equal(slugify('foo&bar'), 'foo-and-bar');
assert.equal(slugify('foo360BAR'), 'foo360-bar');
assert.equal(slugify('FOO360'), 'foo-360');
assert.equal(slugify('FOOBar'), 'foo-bar');
});
test('decamelize acronyms', () => {
assert.equal(slugify('APISection'), 'api-section');
// The word after the acronym has `s` as its second letter, which used to prevent the split.
assert.equal(slugify('HTMLEscape'), 'html-escape');
assert.equal(slugify('XMLMsgBox'), 'xml-msg-box');
// The minimum two-character acronym splits from a following capitalized word.
assert.equal(slugify('IDValue'), 'id-value');
// The minimum uppercase run also splits from a numeric suffix.
assert.equal(slugify('ID2'), 'id-2');
// Acronyms split correctly when preceded by a lowercase word.
assert.equal(slugify('parseXMLDocument'), 'parse-xml-document');
// Multiple acronym-to-word boundaries are handled in the same identifier.
assert.equal(slugify('XMLHttpAPIResponse'), 'xml-http-api-response');
// Numeric acronym suffixes compose with a following capitalized word.
assert.equal(slugify('HTML5Parser'), 'html-5-parser');
// A plural acronym stays intact.
assert.equal(slugify('APIs'), 'apis');
assert.equal(slugify('Util APIs'), 'util-apis');
assert.equal(slugify('APIsAndMore'), 'apis-and-more');
assert.equal(slugify('APIs2'), 'apis2');
// A plural acronym remains intact between camel-cased words.
assert.equal(slugify('getAPIsNow'), 'get-apis-now');
});
test('possessives and contractions', () => {
// Straight apostrophes
assert.equal(slugify('Conway\'s Law'), 'conways-law');
assert.equal(slugify('Conway\'s'), 'conways');
assert.equal(slugify('Don\'t Repeat Yourself'), 'dont-repeat-yourself');
assert.equal(slugify('my parents\' rules'), 'my-parents-rules');
assert.equal(slugify('it-s-hould-not-modify-t-his'), 'it-s-hould-not-modify-t-his');
// Curly/smart apostrophes
assert.equal(slugify('Sindre’s app'), 'sindres-app');
assert.equal(slugify('can’t stop'), 'cant-stop');
assert.equal(slugify('won’t work'), 'wont-work');
// Punctuation after the contraction must not stop it from being collapsed.
assert.equal(slugify('Don\'t!'), 'dont');
assert.equal(slugify('Conway\'s, revisited'), 'conways-revisited');
assert.equal(slugify('it\'s, then'), 'its-then');
assert.equal(slugify('can\'t-stop'), 'cant-stop');
assert.equal(slugify('it\'s...'), 'its');
assert.equal(slugify('Don’t!'), 'dont');
assert.equal(slugify('(it\'s)'), 'its');
assert.equal(slugify('He said “It\'s”'), 'he-said-its');
assert.equal(slugify('user\'s_id'), 'users-id');
// Several contractions in the same string.
assert.equal(slugify('It\'s, Bob\'s, and Sue\'s.'), 'its-bobs-and-sues');
// A digit before the apostrophe counts as the word.
assert.equal(slugify('1990\'s, 2000\'s'), '1990s-2000s');
// Not a contraction when a letter or digit follows.
assert.equal(slugify('foo\'sbar'), 'foo-sbar');
assert.equal(slugify('it\'s2'), 'it-s2');
// An apostrophe that does not end a `'s`/`'t` word is untouched.
assert.equal(slugify('\'tis the season'), 'tis-the-season');
assert.equal(slugify('rock \'n\' roll'), 'rock-n-roll');
// Works with the other options.
assert.equal(slugify('Don\'t! stop', {separator: '_'}), 'dont_stop');
assert.equal(slugify('Don\'t! stop', {separator: ''}), 'dontstop');
assert.equal(slugify('Don\'t Stop, Please', {lowercase: false}), 'Dont-Stop-Please');
// An uppercase contraction is collapsed too when `lowercase` is disabled.
assert.equal(slugify('DON\'T STOP!', {lowercase: false}), 'DONT-STOP');
assert.equal(slugify('IT\'S, THEN', {lowercase: false}), 'ITS-THEN');
// Unicode letters kept by `transliterate: false` count as part of the word on both sides of the apostrophe.
assert.equal(slugify('Don’t!', {transliterate: false}), 'dont');
assert.equal(slugify('Déjà’s vu', {transliterate: false}), 'déjàs-vu');
assert.equal(slugify('foo\'sé', {transliterate: false}), 'foo-sé');
// A character transliteration drops cannot be part of the word, so the contraction still ends there.
assert.equal(slugify('Sindre\'s日記'), 'sindres');
assert.equal(slugify('Sindre\'s日記', {transliterate: false}), 'sindre-s日記');
});
test('custom separator', () => {
assert.equal(slugify('foo bar', {separator: '_'}), 'foo_bar');
assert.equal(slugify('aaa bbb', {separator: ''}), 'aaabbb');
assert.equal(slugify('BAR&baz', {separator: '_'}), 'bar_and_baz');
assert.equal(slugify('Déjà Vu!', {separator: '-'}), 'deja-vu');
assert.equal(slugify('UNICORNS AND RAINBOWS!', {separator: '@'}), 'unicorns@and@rainbows');
assert.equal(slugify('[foo] [bar]', {separator: '.'}), 'foo.bar', 'escape regexp special characters');
// Test multi-character separator collapse
assert.equal(slugify('a b c', {separator: '__'}), 'a__b__c');
assert.equal(slugify('a____b', {separator: '__'}), 'a__b');
assert.equal(slugify('__a__b__', {separator: '__'}), 'a__b');
assert.equal(slugify('foo---bar', {separator: '---'}), 'foo---bar');
// A backslash is kept when it is the separator or a preserved character, and removed otherwise
assert.equal(slugify('foo bar', {separator: '\\'}), String.raw`foo\bar`);
assert.equal(slugify(String.raw`foo\bar baz`, {preserveCharacters: ['\\']}), String.raw`foo\bar-baz`);
assert.equal(slugify(String.raw`foo\bar baz`, {transliterate: false, preserveCharacters: ['\\']}), String.raw`foo\bar-baz`);
assert.equal(slugify(String.raw`foo\bar`), 'foo-bar');
});
test('options set to `undefined` use the defaults', () => {
assert.equal(slugify('Déjà Vu fooBar', {
separator: undefined,
lowercase: undefined,
decamelize: undefined,
customReplacements: undefined,
preserveLeadingUnderscore: undefined,
preserveTrailingDash: undefined,
preserveCharacters: undefined,
transliterate: undefined,
locale: undefined,
}), 'deja-vu-foo-bar');
});
test('a separator containing `$` is inserted literally', () => {
// A separator is a plain string, not a replacement pattern, so `$&`, `$$` and `` $` `` must not be expanded.
assert.equal(slugify('foo bar', {separator: '$&'}), 'foo$&bar');
assert.equal(slugify('foo bar', {separator: '$$'}), 'foo$$bar');
assert.equal(slugify('foo bar', {separator: '$1'}), 'foo$1bar');
assert.equal(slugify('foo bar', {separator: '$`'}), 'foo$`bar');
});
test('custom replacements', () => {
assert.equal(slugify('foo | bar', {
customReplacements: [
['|', ' or '],
],
}), 'foo-or-bar');
assert.equal(slugify('10 | 20 %', {
customReplacements: [
['|', ' or '],
['%', ' percent '],
],
}), '10-or-20-percent');
assert.equal(slugify('I ♥ 🦄', {
customReplacements: [
['♥', ' amour '],
['🦄', ' licorne '],
],
}), 'i-amour-licorne');
assert.equal(slugify('x.y.z', {
customReplacements: [
['.', ''],
],
}), 'xyz');
assert.equal(slugify('Zürich', {
customReplacements: [
['ä', 'ae'],
['ö', 'oe'],
['ü', 'ue'],
['ß', 'ss'],
],
}), 'zuerich');
});
test('custom replacements match normalized text before decamelization', () => {
assert.equal(slugify('Cafe\u{301}Bar', {
customReplacements: [['CaféBar', 'done']],
}), 'done');
assert.equal(slugify('CaféBar', {
customReplacements: [['Cafe\u{301}Bar', 'done']],
}), 'done');
});
test('custom replacements retain their ordering', () => {
const customReplacements = [['foo', 'first'], ['fooBar', 'second']];
assert.equal(slugify('fooBar', {customReplacements}), 'second');
assert.equal(slugify('fooBar', {customReplacements, transliterate: false}), 'first-bar');
});
test('normalization rejects excessive combining marks before applying replacements', () => {
const string = `a${'\u{301}'.repeat(101)}`;
assert.throws(() => slugify(string), RangeError);
assert.throws(() => slugify('foo', {customReplacements: [[string, 'bar']]}), RangeError);
});
for (const transliterate of [true, false]) {
test(`custom replacement keys match before decamelization (transliterate: ${transliterate})`, () => {
assert.equal(slugify('fooBar', {
transliterate,
customReplacements: [['fooBar', 'baz']],
}), 'baz');
});
test(`custom replacement values are decamelized (transliterate: ${transliterate})`, () => {
assert.equal(slugify('foo@bar', {
transliterate,
customReplacements: [['@', 'HelloWorld']],
}), 'foo-hello-worldbar');
assert.equal(slugify('@', {
transliterate,
customReplacements: [['@', 'MÜNCHEN']],
}), transliterate ? 'muenchen' : 'münchen');
});
test(`removing text can expose a camel-case boundary (transliterate: ${transliterate})`, () => {
assert.equal(slugify('foo@Bar', {
transliterate,
customReplacements: [['@', '']],
}), 'foo-bar');
});
test(`equal-length replacements can consume an earlier replacement value (transliterate: ${transliterate})`, () => {
assert.equal(slugify('@', {
transliterate,
customReplacements: [['@', '#'], ['#', 'HelloWorld']],
}), 'hello-world');
});
test(`replacement values are not passed through the same replacements again (transliterate: ${transliterate})`, () => {
assert.equal(slugify('foo', {
transliterate,
customReplacements: [['foo', 'fooBar']],
}), 'foo-bar');
});
test(`custom replacements retain matched-text replacement patterns (transliterate: ${transliterate})`, () => {
assert.equal(slugify('foo', {
transliterate,
customReplacements: [['foo', '$&Bar']],
}), 'foo-bar');
});
test(`custom replacements retain literal-dollar replacement patterns (transliterate: ${transliterate})`, () => {
assert.equal(slugify('@', {
transliterate,
preserveCharacters: ['$'],
customReplacements: [['@', '$$HelloWorld']],
}), '$hello-world');
});
test(`replacement values respect disabled decamelization (transliterate: ${transliterate})`, () => {
assert.equal(slugify('@', {
transliterate,
decamelize: false,
lowercase: false,
customReplacements: [['@', 'HelloWorld']],
}), 'HelloWorld');
});
}
test('custom replacement keys remain case-sensitive', () => {
const options = {customReplacements: [['fooBar', 'done']]};
assert.equal(slugify('fooBar foobar FooBar', options), 'done-foobar-foo-bar');
});
test('custom replacement keys are literal strings', () => {
assert.equal(slugify('foo.Bar fooXBar', {
customReplacements: [['foo.Bar', 'done']],
}), 'done-foo-x-bar');
});
test('the last duplicate replacement overrides earlier values with transliteration', () => {
const customReplacements = [['fooBar', 'first'], ['fooBar', 'last']];
assert.equal(slugify('fooBar', {customReplacements}), 'last');
assert.equal(slugify('fooBar', {customReplacements, transliterate: false}), 'first');
});
test('replacement ordering uses normalized key lengths', () => {
assert.equal(slugify('éxValue', {
customReplacements: [['e\u{301}', 'short'], ['éx', 'long']],
}), 'long-value');
});
test('camel-case replacements can override built-in replacements', () => {
assert.equal(slugify('& 🦄', {
customReplacements: [['&', 'RockAndRoll']],
}), 'rock-and-roll-unicorn');
});
test('a built-in replacement can be disabled with an empty value', () => {
assert.equal(slugify('foo&Bar', {
customReplacements: [['&', '']],
}), 'foo-bar');
});
test('replacement values retain casing when lowercasing is disabled', () => {
assert.equal(slugify('@', {
lowercase: false,
customReplacements: [['@', 'HelloWorld']],
}), 'Hello-World');
});
test('replacement word boundaries use the configured separator', () => {
assert.equal(slugify('foo@bar', {
separator: '__',
customReplacements: [['@', ' HelloWorld ']],
}), 'foo__hello__world__bar');
});
test('preserved characters in replacement values survive decamelization', () => {
assert.equal(slugify('@', {
preserveCharacters: ['#'],
customReplacements: [['@', 'HelloWorld#Topic']],
}), 'hello-world#topic');
});
test('edge preservation still uses the original input with replacements', () => {
assert.equal(slugify('_@-', {
preserveLeadingUnderscore: true,
preserveTrailingDash: true,
customReplacements: [['@', 'HelloWorld']],
}), '_hello-world-');
assert.equal(slugify('@', {
preserveLeadingUnderscore: true,
preserveTrailingDash: true,
customReplacements: [['@', '_HelloWorld-']],
}), 'hello-world');
});
test('replacement values are transliterated with the selected locale', () => {
const customReplacements = [['@', 'RäksmörgåsMenu']];
assert.equal(slugify('@', {customReplacements, locale: 'sv'}), 'raksmorgas-menu');
assert.equal(slugify('@', {customReplacements, locale: 'de'}), 'raeksmoergas-menu');
});
test('decomposed replacement values keep their camel-case boundaries', () => {
const customReplacements = [['@', 'Cafe\u{301}Über']];
assert.equal(slugify('@', {customReplacements}), 'cafe-ueber');
assert.equal(slugify('@', {customReplacements, transliterate: false}), 'cafe\u{301}-über');
});
test('custom replacement keys match literally without transliteration', () => {
assert.equal(slugify('Café', {
transliterate: false,
customReplacements: [['Cafe\u{301}', 'done']],
}), 'café');
});
test('custom replacement arrays are not mutated', () => {
const customReplacements = Object.freeze([
Object.freeze(['@', 'Cafe\u{301}Name']),
Object.freeze(['longerKey', 'value']),
]);
const original = structuredClone(customReplacements);
assert.equal(slugify('@', {customReplacements}), 'cafe-name');
assert.deepEqual(customReplacements, original);
});
test('replacement values cannot bypass the normalization mark limit', () => {
assert.throws(() => slugify('@', {
customReplacements: [['@', `a${'\u{301}'.repeat(101)}`]],
}), RangeError);
});
test('normalization accepts the maximum supported mark run', () => {
const string = `a${'\u{301}'.repeat(100)}`;
assert.equal(slugify(string, {customReplacements: [[string, 'done']]}), 'done');
});
test('replacement results share the counter with equivalent direct input', () => {
const countingSlugify = slugifyWithCounter();
assert.equal(countingSlugify('@', {customReplacements: [['@', 'MÜNCHEN']]}), 'muenchen');
assert.equal(countingSlugify('München'), 'muenchen-2');
assert.equal(countingSlugify('muenchen 2'), 'muenchen-2-2');
});
test('lowercase option', () => {
assert.equal(slugify('foo bar', {lowercase: false}), 'foo-bar');
assert.equal(slugify('BAR&baz', {lowercase: false}), 'BAR-and-baz');
assert.equal(slugify('Déjà Vu!', {separator: '_', lowercase: false}), 'Deja_Vu');
assert.equal(slugify('UNICORNS AND RAINBOWS!', {separator: '@', lowercase: false}), 'UNICORNS@AND@RAINBOWS');
assert.equal(slugify('[foo] [bar]', {separator: '.', lowercase: false}), 'foo.bar', 'escape regexp special characters');
assert.equal(slugify('Foo🦄', {lowercase: false}), 'Foo-unicorn');
});
test('decamelize option', () => {
assert.equal(slugify('fooBar'), 'foo-bar');
--- a/.orivoxx/issue.md
+++ /dev/null
@@ -1,6 +0,0 @@
-# Issue
-
-Add a `maxLength` option to slugify. The returned slug must never be longer than the limit. Truncate to the limit, then remove a trailing separator. If the cut splits a word, prefer cutting at the last separator before it; otherwise hard-truncate the slug. `maxLength: 0` returns an empty string. A negative or non-integer `maxLength` must throw a TypeError. Document the option in `index.d.ts` so the published types match the runtime.
-
-Repository: https://github.com/sindresorhus/slugify
-Base commit: 99b35c2b0d6ccfad2b96ba9ce6997c6365b9a4b7
Run summary
{
"status": "completed",
"exitCode": 0,
"durationMs": 232698,
"adapter": {
"id": "claude-code-openrouter",
"version": "1.0.0",
"label": "Claude Code (anthropic/claude-sonnet-4.5)",
"kind": "harness"
},
"model": {
"provider": "openrouter",
"name": "anthropic/claude-sonnet-4.5",
"baseUrl": "https://openrouter.ai/api/v1"
}
}The score is reproducible from the task, ruleset, scoring configuration, and captured repository text. No model call contributed to it.