Open In App

How to Convert Title to URL Slug using JavaScript ?

Converting a title to a URL slug in JavaScript involves transforming the input text into a format suitable for URLs. This typically entails replacing spaces with dashes, removing special characters, and ensuring lowercase consistency for compatibility and readability in web addresses.

Prerequisite 

Basically below program will convert a title into a URL Slug using JavaScript.



Approach

Example: Below is the basic HTML code implementation:




<!DOCTYPE html>
<html>
    <head>
        <style>
            fieldset.slugify {
                color: #515151;
                border: 1px solid #ccc;
                padding: 15px;
            }
 
            .slugify legend {
                font-size: 16px;
                font-weight: 600;
                padding: 0 10px;
            }
 
            .slugify input {
                display: block;
                padding: 8px;
                margin: 8px;
            }
 
            .slug-output {
                color: #05ab13;
                font-size: 20px;
                font-weight: 500;
            }
        </style>
    </head>
 
    <body>
        <form>
            <fieldset class="slugify">
                <legend>GeeksforGeeks</legend>
 
                <label for="slug-source">
                    Input Title:
                </label>
                <input
                    type="text"
                    value=""
                    id="slug-source"
                />
 
                <label for="slug-target">
                    URL Slug:
                </label>
                <input
                    type="text"
                    value=""
                    id="slug-target"
                />
 
                <button
                    type="button"
                    onClick="myFunction()"
                >
                    Convert
                </button>
 
                <p>
                    <span class="slug-output">
                        Generated URL Slug </span
                    >:
                    <span
                        id="slug-target-span"
                    ></span>
                </p>
            </fieldset>
        </form>
    </body>
</html>




function myFunction() {
 
    const a = document.getElementById("slug-source").value.trim().replace(/\s+/g, " ");;
 
    const b = a.toLowerCase().replace(/ /g, '-')
        .replace(/[^\w-]+/g, '');
 
    document.getElementById("slug-target").value = b;
 
    document.getElementById("slug-target-span").innerHTML = b;
}

Output: Click here to check the live Output.




Article Tags :