### Install Slugify
Source: https://github.com/simov/slugify/blob/master/_autodocs/09-quick-reference.md
Install the slugify library using npm.
```bash
npm install slugify
```
--------------------------------
### Slugify Processing Order Example
Source: https://github.com/simov/slugify/blob/master/_autodocs/03-configuration.md
Walks through the step-by-step application of slugify options, including normalization, character mapping, removal, strict filtering, trimming, space consolidation, and lowercasing. This example highlights the transformation of an input string with specific options.
```javascript
const input = ' HELLO!!! WORLD '
const options = {replacement: '_', lower: true, remove: /[!]/g, trim: true}
// Step 1: Normalize → ' HELLO!!! WORLD '
// Step 2: Map chars → ' HELLO WORLD ' (no chars need mapping in this example)
// Step 3: Remove ! → ' HELLO WORLD '
// Step 4: Trim → 'HELLO WORLD'
// Step 5: Consolidate → 'HELLO_WORLD'
// Step 6: Lowercase → 'hello_world'
// Result: 'hello_world'
```
--------------------------------
### Complete SlugifyOptions Example
Source: https://github.com/simov/slugify/blob/master/_autodocs/02-types.md
Illustrates the usage of all available options within the SlugifyOptions object for comprehensive slug generation.
```typescript
const opts: SlugifyOptions = {
replacement: '_',
remove: /[!@#$%]/g,
lower: true,
strict: false,
locale: 'de',
trim: true
}
slugify('Hello World!!!', opts) // 'hello_world'
```
--------------------------------
### Global Character Map Example
Source: https://github.com/simov/slugify/blob/master/_autodocs/07-architecture.md
Demonstrates the structure of the global character map used for Unicode to ASCII transliteration.
```javascript
{
'À': 'A',
'à': 'a',
'€': 'euro',
'©': '(c)',
'♥': 'love',
// ... 1500+ entries
}
```
--------------------------------
### Browser Usage Example
Source: https://github.com/simov/slugify/blob/master/_autodocs/README.md
Include the slugify.js script in your HTML to use the slugify function globally in the browser. This example demonstrates basic usage after including the script.
```html
```
--------------------------------
### Minimal SlugifyOptions Example
Source: https://github.com/simov/slugify/blob/master/_autodocs/02-types.md
Demonstrates how to use the SlugifyOptions object to override only the replacement character for spaces.
```typescript
const opts: SlugifyOptions = {replacement: '_'}
slugify('hello world', opts) // 'hello_world'
```
--------------------------------
### German Locale Slugification Example
Source: https://github.com/simov/slugify/blob/master/_autodocs/03-configuration.md
Demonstrates using the German locale ('de') for correct 'ß' to 'ss' conversion.
```javascript
slugify('Straße', {locale: 'de', lower: true})
// Result: 'strasse'
```
--------------------------------
### charmap.json Example Entries
Source: https://github.com/simov/slugify/blob/master/_autodocs/05-modules.md
Illustrates the structure of the charmap.json file, used for mapping Unicode characters to ASCII equivalents. This file is read during the build process.
```json
{
"$": "dollar",
"%": "percent",
"&": "and",
"À": "A",
"à": "a",
"Ä": "A",
"ä": "a",
"©": "(c)",
"€": "euro",
"♥": "love"
}
```
--------------------------------
### Slugify Default Behavior Example
Source: https://github.com/simov/slugify/blob/master/_autodocs/03-configuration.md
Illustrates the default behavior of the slugify function when no options are provided. Shows the resulting slug based on default settings for replacement, casing, strictness, locale, and trimming.
```javascript
slugify('Hello World!')
// Uses: replacement='-', lower=false, strict=false, locale=undefined, trim=true, remove=/[^\w\s$*_+~.()"'!\-:@]+/g
// Result: 'Hello-World'
```
--------------------------------
### Slugify with Full Options
Source: https://github.com/simov/slugify/blob/master/_autodocs/01-api-reference.md
Use this example when you need to customize multiple aspects of the slugification process, such as replacement characters, specific characters to remove, case conversion, strict mode, locale, and trimming.
```javascript
slugify('foo bar-baz!!!', {
replacement: '_',
remove: /[!]/g,
lower: true,
strict: false,
locale: 'de',
trim: true
})
```
--------------------------------
### Simple ExtendArgs Example
Source: https://github.com/simov/slugify/blob/master/_autodocs/02-types.md
Shows how to create and use an ExtendArgs object to add custom character mappings for © and ™ symbols.
```typescript
const customMap: ExtendArgs = {
'©': 'copyright',
'™': 'trademark'
}
slugify.extend(customMap)
```
--------------------------------
### Slugify German Locale Example
Source: https://github.com/simov/slugify/blob/master/_autodocs/07-architecture.md
Compares the output of slugifying text with and without a specified German locale, highlighting the differences in transliteration.
```javascript
// Text: 'Müller Straße'
// Global charmap: ü → u, ß → ss
// German locale: ü → ue, ß → ss
slugify('Müller Straße') // 'Muller-Strae' (global)
slugify('Müller Straße', {locale: 'de'}) // 'Mueller-Strasse' (German)
```
--------------------------------
### Default Character Mapping Example
Source: https://github.com/simov/slugify/blob/master/_autodocs/03-configuration.md
Shows the result of slugifying without a specified locale, using the default character map.
```javascript
slugify('Straße', {lower: true})
// Result: 'strae'
```
--------------------------------
### TypeScript Usage with Options
Source: https://github.com/simov/slugify/blob/master/_autodocs/README.md
Import slugify and its options type for use in TypeScript projects. This example defines options and then uses slugify to create a customized slug.
```typescript
import slugify, { SlugifyOptions } from 'slugify'
const options: SlugifyOptions = {
replacement: '-',
lower: true
}
const slug: string = slugify('Hello World', options)
```
--------------------------------
### Space Consolidation Before and After
Source: https://github.com/simov/slugify/blob/master/_autodocs/07-architecture.md
Illustrates the effect of space consolidation, where multiple spaces are reduced to a single replacement character. This example shows the transformation from a string with many spaces to a cleaned-up version.
```plaintext
Before: 'foo bar baz' (multiple spaces from removed chars)
After: 'foo-bar-baz' (single replacement)
```
--------------------------------
### Combine Multiple Slugify Options
Source: https://github.com/simov/slugify/blob/master/_autodocs/06-usage-patterns.md
Apply several slugification options simultaneously for complex transformations. This example combines replacement, removal, case conversion, strict mode, and trimming.
```javascript
const slugify = require('slugify')
const options = {
replacement: '_',
remove: /[!@#$%^&*]/g,
lower: true,
strict: true,
trim: true
}
slugify('HELLO!!! WORLD???', options) // 'hello_world'
slugify('Price: $99.99!', options) // 'price-9999'
slugify(' Special @#$ Chars ', options) // 'special-chars'
```
--------------------------------
### locales.json Structure Example
Source: https://github.com/simov/slugify/blob/master/_autodocs/05-modules.md
Shows the format of locales.json, which provides language-specific character overrides for slugification. These mappings take precedence over the global charmap.
```json
{
"de": {
"locale": "German",
"Ä": "AE",
"ä": "ae",
"Ö": "OE",
"ö": "oe",
"Ü": "UE",
"ü": "ue",
"ß": "ss"
},
"fr": {
"locale": "French",
"%": "pourcent",
"&": "et"
}
}
```
--------------------------------
### String Normalization Example
Source: https://github.com/simov/slugify/blob/master/_autodocs/07-architecture.md
Demonstrates the use of `string.normalize()` to convert strings to NFC form, handling composed versus decomposed Unicode characters. This ensures consistent representation of characters like 'é'.
```plaintext
Input: 'café' (é as single character U+00E9)
Normalized: 'café' (identical in NFC form)
Input: 'café' (e + ´ combining)
Normalized: 'café' (converted to composed form)
```
--------------------------------
### Domain-Specific Character Mappings for Slugify
Source: https://github.com/simov/slugify/blob/master/_autodocs/01-api-reference.md
Define domain-specific character mappings for symbols like copyright, trademark, and currency. This example maps common symbols to their abbreviations.
```javascript
slugify.extend({
'©': 'copyright',
'™': 'trademark',
'®': 'registered',
'€': 'eur',
'£': 'gbp'
})
slugify('Product™ © 2024 - Price: €99')
// 'Product-trademark-c-2024-Price-eur99'
```
--------------------------------
### Locale Overrides Example
Source: https://github.com/simov/slugify/blob/master/_autodocs/07-architecture.md
Shows the nested structure for language-specific character transliterations that can override the global map.
```javascript
{
'de': {
'locale': 'German',
'Ä': 'AE',
'ä': 'ae',
'ß': 'ss'
},
'fr': {
'locale': 'French',
'%': 'pourcent',
'&': 'et'
},
// ... 12 locales total
}
```
--------------------------------
### Character Map Priority Example
Source: https://github.com/simov/slugify/blob/master/_autodocs/03-configuration.md
Demonstrates the priority order of character map lookups: locale-specific, extended, and default global charmaps. Locale mappings take precedence over extended and default mappings.
```javascript
// Default charmap: ß → ss
// German locale charmap: ß → ss (same)
// Extended charmap: ß → eszet
slugify('Straße', {locale: 'de'}) // 'Strae' + 'ss'
slugify('Straße', {}) // 'Strae' + 'ss'
slugify.extend({'ß': 'eszet'})
slugify('Straße', {}) // 'Strae' + 'eszet' (extended applies)
slugify('Straße', {locale: 'de'}) // 'Strae' + 'ss' (locale still takes precedence)
```
--------------------------------
### Load Slugify with AMD (RequireJS)
Source: https://github.com/simov/slugify/blob/master/_autodocs/05-modules.md
Use `require` from AMD to load the slugify module, typically used with RequireJS for managing dependencies in the browser. Ensure slugify is configured as a module in your RequireJS setup.
```javascript
require(['slugify'], function(slugify) {
var slug = slugify('Hello World')
})
```
--------------------------------
### Resetting Slugify Cache
Source: https://github.com/simov/slugify/blob/master/README.md
Explains how to reset the module cache to get a fresh instance of slugify's charMap, which is necessary after extending it if you need to revert to defaults.
```javascript
delete require.cache[require.resolve('slugify')]
var slugify = require('slugify')
```
--------------------------------
### Extend Slugify with Custom Symbols
Source: https://github.com/simov/slugify/blob/master/_autodocs/01-api-reference.md
Add support for custom symbols by extending the internal character map. This example shows how to add mappings for '☢' and '☣'.
```javascript
const slugify = require('slugify')
slugify('unicode ♥ is ☢') // 'unicode-love-is' (☢ not in charmap)
slugify.extend({'☢': 'radioactive', '☣': 'biohazard'})
slugify('unicode ♥ is ☢') // 'unicode-love-is-radioactive'
slugify('watch out ☣!!') // 'watch-out-biohazard'
```
--------------------------------
### Error Handling for Invalid Input
Source: https://github.com/simov/slugify/blob/master/_autodocs/README.md
The slugify function expects a string as its first argument. This example shows how to catch the error thrown when a non-string value, like null, is provided.
```javascript
try {
slugify(null) // First parameter must be string
} catch (err) {
console.error(err.message)
// "slugify: string argument expected"
}
```
--------------------------------
### Basic Slugify Usage
Source: https://github.com/simov/slugify/blob/master/_autodocs/09-quick-reference.md
Demonstrates simple and option-based slug generation. Use the second argument for options or a custom replacement string.
```javascript
const slugify = require('slugify')
// Simple usage
slugify('Hello World')
// → 'Hello-World'
// With options
slugify('Hello World', {lower: true})
// → 'hello-world'
// Shorthand
slugify('Hello World', '_')
// → 'Hello_World'
```
--------------------------------
### Slugify with Default Options
Source: https://github.com/simov/slugify/blob/master/_autodocs/07-architecture.md
Demonstrates calling slugify with only the input string, showing the effective options resolved using hardcoded defaults.
```javascript
slugify('test')
// Effective options:
// {
// replacement: '-', (default)
// remove: /[^\w\s$*_+~.()'!\-:@]+/g, (default)
// lower: false, (default)
// strict: false, (default)
// locale: undefined, (default)
// trim: true (default)
// }
```
--------------------------------
### Basic Slugify Usage
Source: https://github.com/simov/slugify/blob/master/_autodocs/README.md
Demonstrates the basic usage of the slugify function to convert a string into a URL-friendly format. It also shows how to apply options like converting to lowercase.
```javascript
const slugify = require('slugify')
// Basic usage
slugify('Hello World')
// → 'Hello-World'
// With options
slugify('Hello World', {lower: true})
// → 'hello-world'
```
--------------------------------
### Locale-Specific Transliteration with Slugify
Source: https://github.com/simov/slugify/blob/master/_autodocs/01-api-reference.md
Perform locale-specific transliteration for characters. For example, 'ß' can be transliterated to 'ss' in German ('de') locale.
```javascript
slugify('Straße Café', {locale: 'de', lower: true}) // 'strasse-cafe'
slugify('Straße Café', {locale: 'en', lower: true}) // 'strae-cafe'
slugify('Grüße', {locale: 'de', lower: true}) // 'grusse'
```
--------------------------------
### Slugify with Options
Source: https://github.com/simov/slugify/blob/master/README.md
Shows how to use slugify with a configuration object to customize its behavior, such as replacement character, character removal, case conversion, and strict mode.
```javascript
slugify('some string', {
replacement: '-', // replace spaces with replacement character, defaults to `-`
remove: undefined, // remove characters that match regex, defaults to `undefined`
lower: false, // convert to lower case, defaults to `false`
strict: false, // strip special characters except replacement, defaults to `false`
locale: 'vi', // language code of the locale to use
trim: true // trim leading and trailing replacement chars, defaults to `true`
})
```
--------------------------------
### Slugify Processing Pipeline
Source: https://github.com/simov/slugify/blob/master/_autodocs/07-architecture.md
Illustrates the sequential transformations applied to an input string to generate a URL-friendly slug.
```text
Input String
↓
[1] Unicode Normalization (NFC)
↓
[2] Character Splitting
↓
[3] Character Mapping & Replacement
├─ Check locale-specific map
├─ Check global character map
├─ Check extended map (from extend())
└─ Preserve unmapped characters
↓
[4] Character Removal (via regex)
↓
[5] Strict Mode Filtering (optional)
├─ Remove non-alphanumeric except replacement
└─ Applied only if strict: true
↓
[6] Trim Spaces (optional)
├─ Remove leading/trailing spaces
└─ Applied only if trim: true
↓
[7] Space Consolidation
├─ Replace multiple consecutive spaces with replacement
└─ Single replacement applied
↓
[8] Lowercase Conversion (optional)
├─ Convert to lowercase
└─ Applied only if lower: true
↓
Output Slug
```
--------------------------------
### Override Slugify Transliteration
Source: https://github.com/simov/slugify/blob/master/_autodocs/01-api-reference.md
Override existing transliterations to change how specific characters are converted. This example changes the mapping for 'é' from 'e' to 'eh'.
```javascript
const slugify = require('slugify')
slugify('café') // 'cafe' (default é → e)
slugify.extend({'é': 'eh'})
slugify('café') // 'cafe-eh' (now é → eh)
```
--------------------------------
### Basic Slugify Usage
Source: https://github.com/simov/slugify/blob/master/README.md
Demonstrates the basic usage of the slugify function with and without a custom separator.
```javascript
var slugify = require('slugify')
slugify('some string') // some-string
// if you prefer something other than '-' as separator
slugify('some string', '_') // some_string
```
--------------------------------
### Generate E-Commerce Product URLs
Source: https://github.com/simov/slugify/blob/master/_autodocs/06-usage-patterns.md
Create product URLs for e-commerce sites by slugifying category and product names, and appending the SKU.
```javascript
const slugify = require('slugify')
function generateProductUrl(category, productName, sku) {
const catSlug = slugify(category, {lower: true, strict: true})
const nameSlug = slugify(productName, {lower: true, strict: true})
return `/products/${catSlug}/${nameSlug}-${sku}`.toLowerCase()
}
generateProductUrl('Electronics', 'Wireless Mouse', 'SKU-12345')
// '/products/electronics/wireless-mouse-sku-12345'
```
--------------------------------
### Generate German Umlaut Slug
Source: https://github.com/simov/slugify/blob/master/_autodocs/09-quick-reference.md
Handle German umlauts by specifying the locale as 'de' and converting to lowercase. For example, 'Straße' becomes 'strasse'.
```javascript
slugify(text, {locale: 'de', lower: true})
// Straße → strasse
```
--------------------------------
### Slugify Global State Extension (Good Practice)
Source: https://github.com/simov/slugify/blob/master/_autodocs/07-architecture.md
Shows the recommended approach for extending the global character map by performing the extension once at application startup to avoid thread-safety issues and global scope pollution.
```javascript
// GOOD: Extend once at startup
// In main.js:
slugify.extend({'é': 'eh'})
// In all modules:
const slugify = require('slugify')
slugify('Café') // Uses extended map from initialization
```
--------------------------------
### Remove Specific Characters
Source: https://github.com/simov/slugify/blob/master/_autodocs/README.md
Use the 'remove' option to specify a regular expression for characters to be removed from the slug. This example removes dollar signs and exclamation marks.
```javascript
slugify('Price: $99!', {remove: /[$!]/g})
// → 'Price-99'
```
--------------------------------
### Slugify Shorthand Syntax for Replacement
Source: https://github.com/simov/slugify/blob/master/_autodocs/03-configuration.md
Demonstrates the convenience of using a string as the second argument to specify the replacement character. This is equivalent to providing a configuration object with the 'replacement' option.
```javascript
slugify('hello world', '_')
// Equivalent to:
slugify('hello world', {replacement: '_'})
```
--------------------------------
### Avoid Repeated Charmap Extensions
Source: https://github.com/simov/slugify/blob/master/_autodocs/06-usage-patterns.md
Extend the charmap once at startup to avoid performance degradation. Repeatedly calling `slugify.extend` within a function is inefficient.
```javascript
const slugify = require('slugify')
// BAD: Extends on every call
function makeSlug(text) {
slugify.extend({'☢': 'radioactive'}) // Repeated unnecessarily
return slugify(text)
}
// GOOD: Extend once at module initialization
slugify.extend({'☢': 'radioactive'})
function makeSlug(text) {
return slugify(text)
}
```
--------------------------------
### Handling Unicode Symbols
Source: https://github.com/simov/slugify/blob/master/README.md
Demonstrates the default behavior of stripping unsupported Unicode symbols and how to extend the library to support them.
```javascript
slugify('unicode ♥ is ☢') // unicode-love-is
```
```javascript
slugify.extend({'☢': 'radioactive'})
slugify('unicode ♥ is ☢') // unicode-love-is-radioactive
```
--------------------------------
### Basic Slugify Usage
Source: https://github.com/simov/slugify/blob/master/_autodocs/01-api-reference.md
Demonstrates the basic usage of the slugify function with default options. The default separator is a hyphen and strings are not lowercased.
```javascript
const slugify = require('slugify')
slugify('Hello World') // 'Hello-World'
slugify('Hello World!!') // 'Hello-World'
slugify('Some String') // 'Some-String'
```
--------------------------------
### Minimal Slug (Alphanumeric Only)
Source: https://github.com/simov/slugify/blob/master/_autodocs/README.md
The 'strict' option, when set to true, ensures only alphanumeric characters are kept, and 'lower' converts the slug to lowercase. This example demonstrates creating a strictly lowercase alphanumeric slug.
```javascript
slugify('Hello@World!', {strict: true, lower: true})
// → 'hello-world'
```
--------------------------------
### Basic URL Slug Generation
Source: https://github.com/simov/slugify/blob/master/_autodocs/README.md
Use this for creating simple, lowercase slugs for URLs from a given string. Ensure the slugify function is imported.
```javascript
slugify('My Blog Post Title', {lower: true})
// → 'my-blog-post-title'
```
--------------------------------
### CommonJS Import
Source: https://github.com/simov/slugify/blob/master/_autodocs/09-quick-reference.md
Demonstrates how to import the slugify function using CommonJS module syntax. Supports both default and named exports.
```javascript
// Default export
const slugify = require('slugify')
// Named export
const slugify = require('slugify').default
```
--------------------------------
### Space Consolidation using Regex
Source: https://github.com/simov/slugify/blob/master/_autodocs/07-architecture.md
Shows how a global regular expression replacement is used to collapse multiple whitespace characters into a single separator. This is typically applied after character removals that might introduce extra spaces.
```javascript
slug.replace(/\s+/g, replacement)
```
--------------------------------
### slugify() Function
Source: https://github.com/simov/slugify/blob/master/_autodocs/09-quick-reference.md
The main function to convert a string into a slug. It accepts a string and optional configuration options.
```APIDOC
## slugify()
### Description
Converts a given string into a URL-friendly slug.
### Method
Function
### Parameters
- **string** (string) - Required - The input string to be slugified.
- **options** (object) - Optional - Configuration object for slugification.
### Returns
- **string** - The generated slug.
### Throws
- **Error** - Thrown if the first parameter is not a string.
```
--------------------------------
### slugify() Function
Source: https://github.com/simov/slugify/blob/master/_autodocs/MANIFEST.txt
The main function to convert a string into a URL-friendly slug. It accepts a string and an optional options object.
```APIDOC
## slugify()
### Description
Converts a given string into a URL-friendly slug.
### Method
Function Call
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Function Signature
`slugify(input: string, options?: SlugifyOptions): string`
### Parameters
- **input** (string) - Required - The string to be slugified.
- **options** (SlugifyOptions) - Optional - An object containing configuration options for slugification.
### Return Type
- `string` - The generated slug.
### Request Example
```javascript
slugify('Hello World!'); // Returns 'hello-world'
slugify(' Extra Spaces ', { trim: false }); // Returns ' extra spaces '
```
### Response
#### Success Response
- `string` - The slugified string.
#### Response Example
```json
{
"example": "hello-world"
}
```
```
--------------------------------
### Importing slugify in CommonJS and ES6
Source: https://github.com/simov/slugify/blob/master/_autodocs/05-modules.md
Demonstrates how to import the slugify function using CommonJS require statements and ES6 import syntax. This is useful for integrating the library into different JavaScript module systems.
```javascript
// CommonJS
const slugify = require('slugify')
const slugify_default = require('slugify').default
// ES6 import (via TypeScript definitions)
import slugify from 'slugify'
```
--------------------------------
### Load Slugify in Browser (ES6 Module)
Source: https://github.com/simov/slugify/blob/master/_autodocs/05-modules.md
Import the slugify module using ES6 import syntax when using a module bundler or in environments that support native ES modules. Ensure the path to `slugify.js` is correct.
```javascript
import slugify from './slugify.js'
const slug = slugify('Hello World')
```
--------------------------------
### Character Mapping Algorithm Logic
Source: https://github.com/simov/slugify/blob/master/_autodocs/07-architecture.md
Illustrates the steps involved in the character mapping process, including locale and global map lookups, substitution, and removal of unmapped characters. This algorithm aims for single-pass processing.
```plaintext
For each character in string:
1. Check if character exists in locale map
2. If not found, check global charmap
3. If not found, use original character
4. If mapped value equals replacement character, substitute space instead
5. Remove unmapped characters via regex
Accumulate into result string
```
--------------------------------
### Generate Basic Slugs
Source: https://github.com/simov/slugify/blob/master/_autodocs/06-usage-patterns.md
Convert strings to URL-friendly slugs using default settings. Handles spaces and common special characters.
```javascript
const slugify = require('slugify')
slugify('Hello World') // 'Hello-World'
slugify('The Quick Brown Fox') // 'The-Quick-Brown-Fox'
slugify('Café au Lait') // 'Cafe-au-Lait'
slugify('Special Characters!!!') // 'Special-Characters'
```
--------------------------------
### Generate File Names from Titles
Source: https://github.com/simov/slugify/blob/master/_autodocs/06-usage-patterns.md
Create safe and consistent file names from titles by converting them to a slug format with a specified extension.
```javascript
const slugify = require('slugify')
function generateFileName(title, extension = 'txt') {
const slug = slugify(title, {lower: true, strict: true})
return `${slug}.${extension}`
}
generateFileName('My Document', 'pdf') // 'my-document.pdf'
generateFileName('Report-2024', 'xlsx') // 'report-2024.xlsx'
```
--------------------------------
### Catching 'slugify: string argument expected' Error
Source: https://github.com/simov/slugify/blob/master/_autodocs/04-errors.md
Demonstrates how to use a try-catch block to handle the specific error thrown when a non-string argument is passed to slugify.
```javascript
const slugify = require('slugify')
try {
slugify(undefined)
} catch (err) {
if (err.message === 'slugify: string argument expected') {
console.error('Input must be a string')
}
}
```
--------------------------------
### replace(string, options)
Source: https://github.com/simov/slugify/blob/master/_autodocs/05-modules.md
Processes a given string to create a URL-friendly slug. It handles character replacement, normalization, trimming, and optional lowercasing based on provided options.
```APIDOC
## replace(string, options)
### Description
Processes a given string to create a URL-friendly slug. It handles character replacement, normalization, trimming, and optional lowercasing based on provided options.
### Signature
```javascript
function replace(string, options)
```
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **string** (string) - Required - The input string to be slugified.
- **options** (object) - Optional - Configuration for slugification.
- **locale** (string) - Specifies the locale for character mapping.
- **replacement** (string) - The character to use for replacing spaces (default: '-').
- **trim** (boolean) - Whether to trim leading/trailing spaces (default: true).
- **strict** (boolean) - Whether to remove non-alphanumeric characters (optional).
- **lowercase** (boolean) - Whether to convert the string to lowercase (default: true).
### Request Example
```json
{
"string": "Hello World!",
"options": {
"locale": "en",
"replacement": "_",
"trim": true,
"lowercase": true
}
}
```
### Response
#### Success Response (200)
- **slug** (string) - The generated slug.
#### Response Example
```json
{
"slug": "hello_world_"
}
```
```
--------------------------------
### Import Slugify Module
Source: https://github.com/simov/slugify/blob/master/_autodocs/01-api-reference.md
Import the slugify function from the module. Supports both commonJS and default export styles.
```javascript
const slugify = require('slugify')
// or with default export
const slugify = require('slugify').default
```
```typescript
import slugify from 'slugify'
```
--------------------------------
### Generate Multi-Language Slug
Source: https://github.com/simov/slugify/blob/master/_autodocs/09-quick-reference.md
Demonstrates generating slugs for multi-language text, with and without locale-specific options.
```javascript
const text = 'Café Grüße'
slugify(text) // → 'Cafe-Grue'
slugify(text, {locale: 'de', lower: true}) // → 'cafe-grusse'
```
--------------------------------
### Generate File Name Slug
Source: https://github.com/simov/slugify/blob/master/_autodocs/09-quick-reference.md
Create a lowercase slug suitable for file names, appending a file extension.
```javascript
slugify('Report - 2024 (Draft)', {lower: true}) + '.pdf'
// → 'report-2024-draft.pdf'
```
--------------------------------
### Generate Blog Post URL Slugs
Source: https://github.com/simov/slugify/blob/master/_autodocs/06-usage-patterns.md
Create SEO-friendly URL slugs for blog posts by converting titles to lowercase, replacing spaces with hyphens, and removing special characters.
```javascript
const slugify = require('slugify')
function generateBlogSlug(title) {
return slugify(title, {
replacement: '-',
lower: true,
strict: false,
trim: true
})
}
generateBlogSlug('Getting Started with Node.js') // 'getting-started-with-nodejs'
generateBlogSlug('React Best Practices!') // 'react-best-practices'
generateBlogSlug('Why C++ is Awesome?') // 'why-c-is-awesome'
```
--------------------------------
### Create URL-Safe Path Segments
Source: https://github.com/simov/slugify/blob/master/_autodocs/06-usage-patterns.md
Generate URL-safe path segments by slugifying each segment and joining them with forward slashes.
```javascript
const slugify = require('slugify')
function createUrlPath(segments) {
return segments.map(seg =>
slugify(seg, {lower: true, strict: true})
).join('/')
}
createUrlPath(['Products', 'Laptops & Desktops', 'Gaming Rigs'])
// 'products/laptops-desktops/gaming-rigs'
```
--------------------------------
### Comparing Multiple Locale Slugifications
Source: https://github.com/simov/slugify/blob/master/_autodocs/03-configuration.md
Illustrates how different locales ('de' and 'fr') produce different results for the same input string.
```javascript
const text = 'Café Grüße'
slugify(text, {locale: 'de', lower: true}) // 'cafe-grusse'
slugify(text, {locale: 'fr', lower: true}) // 'cafe-grue'
```
--------------------------------
### Slugify Global State Extension (Bad Practice)
Source: https://github.com/simov/slugify/blob/master/_autodocs/07-architecture.md
Demonstrates the incorrect way to extend the global character map, which mutates state shared across all callers and can lead to unexpected behavior in multi-threaded environments.
```javascript
// BAD: Mutates global state
slugify.extend({'é': 'eh'})
slugify('Café') // Uses extended map
// Now ALL callers see this mapping
```
--------------------------------
### Slugify Locale Lookup Chain
Source: https://github.com/simov/slugify/blob/master/_autodocs/07-architecture.md
Illustrates the process of slugifying text with locale-specific transliterations, showing the fallback mechanism from locale-specific maps to a global charMap.
```text
slugify(text, {locale: 'de'})
↓
Fetch locales['de']
↓
Is it defined? YES → Use German map
↓
For each character:
1. Check German map (locales['de'])
2. If not found, check global charMap
3. If still not found, preserve character
↓
Result with German-specific transliterations
```
--------------------------------
### Default Character Map: Symbols & Math
Source: https://github.com/simov/slugify/blob/master/_autodocs/03-configuration.md
Details the default mapping for common symbols and mathematical characters to their ASCII representations.
```text
© → (c)
® → (r)
™ → tm
† → +
• → *
… → ...
∂ → d
∆ → delta
∑ → sum
∞ → infinity
♥ → love
```
--------------------------------
### slugify.extend() Method
Source: https://github.com/simov/slugify/blob/master/_autodocs/MANIFEST.txt
Extends the character map with custom replacements for specific characters or patterns.
```APIDOC
## slugify.extend()
### Description
Allows extending the default character map with custom replacements, enabling support for additional characters or specific transformations.
### Method
Function Call
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Function Signature
`slugify.extend(customMap: ExtendArgs): void`
### Parameters
- **customMap** (ExtendArgs) - Required - An object where keys are characters or patterns to replace, and values are their replacements.
### Return Type
None (modifies the internal character map).
### Request Example
```javascript
slugify.extend({
'€': 'euro',
'£': 'pound'
});
slugify('Price: €10 / £5'); // Returns 'price-euro10-pound5'
```
### Response
#### Success Response
No direct response, modifies the internal state.
#### Response Example
```json
{
"example": "(no response body)"
}
```
```
--------------------------------
### Locale Configuration JSON Structure
Source: https://github.com/simov/slugify/blob/master/_autodocs/03-configuration.md
Defines the structure for locale configuration files, specifying language name and character mappings.
```json
{
"locale": "Language Name",
"char1": "mapping1",
"char2": "mapping2"
}
```
--------------------------------
### Generate Blog Post URL Slug
Source: https://github.com/simov/slugify/blob/master/_autodocs/09-quick-reference.md
Use this snippet to create a URL-friendly slug for a blog post title. Converts text to lowercase.
```javascript
slugify('My Awesome Blog Post!', {lower: true})
// → 'my-awesome-blog-post'
```
--------------------------------
### Shorthand for Custom Separators
Source: https://github.com/simov/slugify/blob/master/_autodocs/06-usage-patterns.md
Use a simple string as the second argument to quickly set a custom replacement character for slugs.
```javascript
const slugify = require('slugify')
slugify('Hello World', '_') // Same as {replacement: '_'}
slugify('Hello World', '~') // Same as {replacement: '~'}
slugify('Hello World', '') // Same as {replacement: ''}
```
--------------------------------
### Generate Lowercase Slugs
Source: https://github.com/simov/slugify/blob/master/_autodocs/06-usage-patterns.md
Create slugs in all lowercase for consistent URL formatting. Useful for case-insensitive routing.
```javascript
const slugify = require('slugify')
slugify('Hello WORLD', {lower: true}) // 'hello-world'
slugify('BlogPost Title', {lower: true}) // 'blogpost-title'
slugify('UPPERCASE', {lower: true}) // 'uppercase'
```
--------------------------------
### Custom Character Mappings for Slugify
Source: https://github.com/simov/slugify/blob/master/_autodocs/README.md
Extend the slugify library with custom character mappings to handle specific symbols or abbreviations. Use `slugify.extend()` to add your mappings before calling slugify.
```javascript
slugify.extend({
'©': 'copyright',
'™': 'trademark',
'€': 'euro'
})
slugify('Product™ © Company - €99')
// → 'Product-trademark-c-Company-euro99'
```
--------------------------------
### Create Database Identifiers
Source: https://github.com/simov/slugify/blob/master/_autodocs/06-usage-patterns.md
Generate database-friendly identifiers from names by converting to lowercase, replacing invalid characters with underscores, and removing disallowed characters.
```javascript
const slugify = require('slugify')
function createDatabaseId(name) {
return slugify(name, {
replacement: '_',
lower: true,
strict: true,
remove: /[^a-z0-9_]/g
})
}
createDatabaseId('User Profile Table') // 'user_profile_table'
createDatabaseId('API v2.0 Response') // 'api_v20_response'
```
--------------------------------
### Slugify Options Interface
Source: https://github.com/simov/slugify/blob/master/_autodocs/09-quick-reference.md
Defines the available options for customizing slug generation, including replacement, removal of characters, case, strictness, locale, and trimming.
```typescript
interface SlugifyOptions {
replacement?: string; // Default: '-'
remove?: RegExp; // Default: /[^\w\s$*_+~.()"'!\-:@]+/g
lower?: boolean; // Default: false
strict?: boolean; // Default: false
locale?: string; // Default: undefined
trim?: boolean; // Default: true
}
```
--------------------------------
### Slugify with Shorthand Replacement
Source: https://github.com/simov/slugify/blob/master/_autodocs/01-api-reference.md
Use this shorthand when you only need to change the character used to replace spaces. This is equivalent to providing a full options object with only the 'replacement' field set.
```javascript
slugify('foo bar', '_') // Equivalent to {replacement: '_'}
```
--------------------------------
### Slugify String Replacement Function
Source: https://github.com/simov/slugify/blob/master/_autodocs/05-modules.md
This function processes a string to create a URL-friendly slug. It handles Unicode normalization, character mapping, trimming, and case conversion based on provided options.
```javascript
function replace(string, options) {
// Type Check
if (typeof string !== 'string') {
throw new TypeError('Expected a string.');
}
// Option Normalization
if (typeof options === 'string') {
options = { locale: options };
}
options = options || {};
// Locale Lookup
const locale = locales[options.locale] || {};
// Default Values
const replacement = options.replacement || '-';
const trim = options.trim === undefined ? true : !!options.trim;
// Character Processing
let slug = String(string)
.normalize('NFD')
.replace(/["'`’‘“”;:]/g, '') // Remove punctuation
.replace(/\s+/g, replacement) // Replace spaces with replacement
.replace(/[^-a-zA-Z0-9+.]/g, (char) => locale[char] || '');
// Strict Mode
if (options.strict) {
slug = slug.replace(/[^-a-zA-Z0-9+.]/g, '');
}
// Trimming
if (trim) {
const trimRegex = new RegExp(`^${replacement}+|${replacement}+$`, 'g');
slug = slug.replace(trimRegex, '');
}
// Consolidation
const consolidationRegex = new RegExp(`${replacement}{2,}`, 'g');
slug = slug.replace(consolidationRegex, replacement);
// Lowercase
if (options.lower === undefined || options.lower === true) {
slug = slug.toLowerCase();
}
return slug;
}
```
--------------------------------
### Batch Process Strings with Slugify
Source: https://github.com/simov/slugify/blob/master/_autodocs/06-usage-patterns.md
Process multiple strings efficiently by mapping over an array and applying slugify to each item. This is useful for generating slugs for lists of titles or articles.
```javascript
const slugify = require('slugify')
// Create a batch processor
function slugifyBatch(items, options) {
return items.map(item => slugify(item, options))
}
const titles = [
'First Post',
'Second Article',
'Third Tutorial'
]
const slugs = slugifyBatch(titles, {lower: true})
// ['first-post', 'second-article', 'third-tutorial']
```
--------------------------------
### Load Slugify in Node.js (TypeScript)
Source: https://github.com/simov/slugify/blob/master/_autodocs/05-modules.md
Import the slugify module using ES6 import syntax in a TypeScript project. Ensure your `tsconfig.json` is configured for module resolution.
```typescript
import slugify from 'slugify'
const slug = slugify('Hello World')
```
--------------------------------
### Load Slugify in Node.js (CommonJS)
Source: https://github.com/simov/slugify/blob/master/_autodocs/05-modules.md
Use `require` to import the slugify module in a CommonJS environment. This is the standard way to load modules in older Node.js versions.
```javascript
const slugify = require('slugify')
const slug = slugify('Hello World')
```
--------------------------------
### Defensive Locale Handling for slugify
Source: https://github.com/simov/slugify/blob/master/_autodocs/04-errors.md
Implement checks for supported locales before passing the locale option to slugify. Warn the user if an unsupported locale is provided and default to the library's default behavior.
```javascript
const slugify = require('slugify')
const SUPPORTED_LOCALES = ['de', 'fr', 'es', 'it', 'pt']
function slugifyWithLocale(text, locale) {
const options = {}
if (locale && SUPPORTED_LOCALES.includes(locale)) {
options.locale = locale
} else if (locale) {
console.warn(`Unsupported locale "${locale}", using default`)
}
return slugify(text, options)
}
```
--------------------------------
### Slugify Configuration Object Schema
Source: https://github.com/simov/slugify/blob/master/_autodocs/03-configuration.md
Defines the structure of the configuration object accepted by the slugify function. Properties are optional and have default values.
```typescript
{
replacement?: string;
remove?: RegExp;
lower?: boolean;
strict?: boolean;
locale?: string;
trim?: boolean;
}
```
--------------------------------
### Default Character Map: Currency Symbols
Source: https://github.com/simov/slugify/blob/master/_autodocs/03-configuration.md
Displays the default mapping for various currency symbols to their ASCII representations.
```text
¢ → cent
£ → pound
¤ → currency
¥ → yen
€ → euro
₹ → indian rupee
```
--------------------------------
### Generate Slug with No Spaces
Source: https://github.com/simov/slugify/blob/master/_autodocs/09-quick-reference.md
Create a slug without any spaces between words by setting the replacement character to an empty string.
```javascript
slugify(text, {replacement: ''})
```
--------------------------------
### Generate Database Identifier Slug
Source: https://github.com/simov/slugify/blob/master/_autodocs/09-quick-reference.md
Create a strict, lowercase slug for database identifiers, using underscores as replacements.
```javascript
slugify('User Profile Table', {lower: true, strict: true, replacement: '_'})
// → 'user_profile_table'
```
--------------------------------
### Handle non-string inputs by converting to string
Source: https://github.com/simov/slugify/blob/master/_autodocs/09-quick-reference.md
Passing a non-string value directly to `slugify` will throw a type error. Convert the input to a string using `String()` before passing it to `slugify` to avoid errors.
```javascript
slugify(123) // Throws!
```
```javascript
slugify(String(123)) // '123'
```
--------------------------------
### Multi-Language Slug Generation
Source: https://github.com/simov/slugify/blob/master/_autodocs/06-usage-patterns.md
Support multi-language slug generation by using locale-specific transliteration options provided by the slugify library.
```javascript
const slugify = require('slugify')
const LOCALE_MAP = {
'de': 'de',
'de-DE': 'de',
'fr': 'fr',
'fr-FR': 'fr',
'es': 'es',
'es-ES': 'es',
'pt-BR': 'pt',
'en': undefined // Use default
}
function generateLocalizedSlug(text, locale) {
const slugLocale = LOCALE_MAP[locale]
const options = {lower: true}
if (slugLocale) {
options.locale = slugLocale
}
return slugify(text, options)
}
generateLocalizedSlug('Straße', 'de') // 'strasse'
generateLocalizedSlug('Straße', 'en') // 'strae'
generateLocalizedSlug('Café', 'fr') // 'cafe'
generateLocalizedSlug('Niño', 'es') // 'nino'
```
--------------------------------
### Avoid extending slugify globally mid-process
Source: https://github.com/simov/slugify/blob/master/_autodocs/09-quick-reference.md
The `extend()` method modifies the global character map. Call it once at startup to ensure all subsequent slugify calls use the extended map consistently.
```javascript
slugify.extend({...})
slugify('text') // Uses extended map
slugify('other') // ALSO uses extended map!
```
```javascript
slugify.extend({...}) // Global change
// Now all calls use extended map
```
--------------------------------
### slugify Function
Source: https://github.com/simov/slugify/blob/master/_autodocs/01-api-reference.md
The slugify function converts a string into a URL-friendly slug. It accepts an optional configuration object to customize its behavior.
```APIDOC
## slugify Function
### Description
Converts a string into a URL-friendly slug. It accepts an optional configuration object to customize its behavior.
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Parameters (for slugify function)
- **text** (string) - Required - The input string to slugify.
- **options** (SlugifyOptions) - Optional - An object to configure slug generation. See `SlugifyOptions` interface for details.
### SlugifyOptions Interface
#### Fields
- **replacement** (string) - Optional - Character(s) to replace spaces with. Defaults to `'-'`. If replacement equals the transliterated character, that character becomes a space instead.
- **remove** (RegExp) - Optional - Pattern of characters to remove after transliteration. Defaults to `/[^\w\s$*_+~.()"'\-:@]+/g`. Must be a character class with global flag. If string provided instead of RegExp, treated as single character to remove.
- **lower** (boolean) - Optional - Convert result to lowercase. Defaults to `false`.
- **strict** (boolean) - Optional - Remove all special characters except alphanumeric. Defaults to `false`.
- **locale** (string) - Optional - ISO 639-1 language code for locale-specific transliteration. Supported locales: bg, de, es, fr, pt, uk, vi, da, nb, it, nl, sv. Defaults to `undefined`.
- **trim** (boolean) - Optional - Trim leading/trailing replacement characters. Defaults to `true`.
### Usage Examples
Full options object:
```javascript
slugify('foo bar-baz!!!', {
replacement: '_',
remove: /[!]/g,
lower: true,
strict: false,
locale: 'de',
trim: true
})
```
Shorthand (string as replacement):
```javascript
slugify('foo bar', '_') // Equivalent to {replacement: '_'}
```
```
--------------------------------
### Handle International Characters with Locales
Source: https://github.com/simov/slugify/blob/master/_autodocs/06-usage-patterns.md
Generate slugs for various languages, correctly transliterating accented and special Unicode characters based on locale.
```javascript
const slugify = require('slugify')
// German (ß, ä, ö, ü special handling)
slugify('Straße', {locale: 'de', lower: true}) // 'strasse'
slugify('Grüße Äpfel', {locale: 'de', lower: true}) // 'grusse-apfel'
// French (with © and other symbols)
slugify('Café © 2024', {locale: 'fr', lower: true}) // 'cafe-c-2024'
// Spanish
slugify('Niño Español', {locale: 'es', lower: true}) // 'nino-espanol
// Russian/Cyrillic
slugify('Привет Мир', {locale: 'uk'}) // 'Privet-Mir'
// Vietnamese
slugify('Xin Đón', {locale: 'vi'}) // 'Xin-Don'
// Default (no locale)
slugify('Straße Café') // 'Strae-Cafe'
```
--------------------------------
### International Text Slug Generation with Locales
Source: https://github.com/simov/slugify/blob/master/_autodocs/README.md
Handle international characters by specifying the appropriate locale. This ensures correct transliteration for languages like German and French. Ensure the slugify function is imported.
```javascript
// German
slugify('Straße Café', {locale: 'de', lower: true})
// → 'strasse-cafe'
```
```javascript
// French
slugify('Café Français', {locale: 'fr', lower: true})
// → 'cafe-francais'
```