How to convert Title to URL Slug using JavaScript?

Overview

The conversion of a title to URL Slug is also known as "Slugify" a title. A URL Slug refers to a descriptive, readable identifier attached to a page's URL that describes the content. Converting titles to URL-friendly slugs involves using JavaScript string methods like toLowerCase(), replace(), and trim().

Algorithm

  • Step 1 ? Create HTML input elements with IDs "title" and "urlSlug" for input and output, plus a button with onclick event.

  • Step 2 ? Create a convert() function to handle the transformation.

  • Step 3 ? Get the title value using document.getElementById("title").value.

  • Step 4 ? Convert to lowercase using toLowerCase().

  • Step 5 ? Remove leading/trailing spaces with trim().

  • Step 6 ? Replace spaces and special characters with hyphens using replace() with regex pattern.

  • Step 7 ? Display the generated slug in the output field.

Basic Implementation

function createSlug(title) {
    return title
        .toLowerCase()           // Convert to lowercase
        .trim()                  // Remove leading/trailing spaces
        .replace(/[^a-z0-9]+/g, '-')  // Replace non-alphanumeric with hyphens
        .replace(/^-+|-+$/g, '');     // Remove leading/trailing hyphens
}

// Test the function
console.log(createSlug("How to Learn JavaScript Quickly"));
console.log(createSlug("  Web Development Tips & Tricks  "));
console.log(createSlug("Node.js vs Python: Which is Better?"));
how-to-learn-javascript-quickly
web-development-tips-tricks
node-js-vs-python-which-is-better

Complete HTML Example

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Convert Title to URL Slug</title>
    <style>
        .container { max-width: 500px; margin: 20px auto; padding: 20px; }
        input { width: 100%; padding: 10px; margin: 5px 0; border: 1px solid #ddd; }
        button { padding: 10px 20px; background: #007bff; color: white; border: none; cursor: pointer; }
        .slug-output { background: #f8f9fa; color: #28a745; }
    </style>
</head>
<body>
    <div class="container">
        <h3>Title to URL Slug Converter</h3>
        
        <label>Enter Title:</label>
        <input type="text" id="title" placeholder="Enter your title here..." />
        
        <label>Generated URL Slug:</label>
        <input type="text" id="urlSlug" class="slug-output" placeholder="Slug will appear here..." readonly />
        
        <button onclick="convertToSlug()">Convert to Slug</button>
    </div>

    <script>
        function convertToSlug() {
            const title = document.getElementById('title').value;
            
            if (title.trim() === '') {
                alert('Please enter a title');
                return;
            }
            
            const slug = title
                .toLowerCase()                    // Convert to lowercase
                .trim()                          // Remove leading/trailing spaces
                .replace(/[^a-z0-9\s-]/g, '')   // Remove special characters except spaces and hyphens
                .replace(/\s+/g, '-')           // Replace spaces with hyphens
                .replace(/-+/g, '-')            // Replace multiple hyphens with single hyphen
                .replace(/^-+|-+$/g, '');       // Remove leading/trailing hyphens
            
            document.getElementById('urlSlug').value = slug;
        }
        
        // Optional: Convert as user types
        document.getElementById('title').addEventListener('input', convertToSlug);
    </script>
</body>
</html>

Advanced Slug Function

function advancedSlug(title, options = {}) {
    const defaults = {
        separator: '-',
        lowercase: true,
        maxLength: 100
    };
    
    const config = { ...defaults, ...options };
    
    let slug = title;
    
    // Convert to lowercase if specified
    if (config.lowercase) {
        slug = slug.toLowerCase();
    }
    
    // Remove special characters and replace spaces
    slug = slug
        .trim()
        .replace(/[^a-z0-9\s-]/gi, '')        // Remove special chars
        .replace(/\s+/g, config.separator)    // Replace spaces
        .replace(new RegExp(`\${config.separator}+`, 'g'), config.separator)  // Remove duplicate separators
        .replace(new RegExp(`^\${config.separator}+|\${config.separator}+$`, 'g'), ''); // Remove leading/trailing separators
    
    // Limit length if specified
    if (config.maxLength && slug.length > config.maxLength) {
        slug = slug.substring(0, config.maxLength).replace(new RegExp(`\${config.separator}[^\${config.separator}]*$`), '');
    }
    
    return slug;
}

// Test different configurations
console.log(advancedSlug("JavaScript: The Complete Guide!"));
console.log(advancedSlug("React & Vue Comparison", { separator: '_' }));
console.log(advancedSlug("Very Long Article Title That Should Be Truncated", { maxLength: 20 }));
javascript-the-complete-guide
react_vue_comparison
very-long-article

Key Features

Feature Purpose Method
Lowercase conversion URL consistency toLowerCase()
Space removal Clean boundaries trim()
Character replacement URL-safe format replace() with regex
Length limiting SEO optimization substring()

Common Use Cases

  • Blog URLs: Converting article titles to SEO-friendly URLs

  • Product Pages: Creating clean product URLs from names

  • File Naming: Converting titles to valid filenames

  • API Endpoints: Creating consistent resource identifiers

Conclusion

URL slugs improve SEO rankings and user experience by creating readable, descriptive URLs. The key is combining toLowerCase(), trim(), and replace() methods with proper regex patterns to handle special characters and spaces effectively.

Updated on: 2026-03-15T23:19:01+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements