How to Convert Title to URL Slug using JavaScript ?

Given a title and the task is to convert the title into a URL slug using JavaScript. In this article, we will use HTML to design the basic structure of the body, CSS is used to set the style of the body, and JavaScript is used to implement the logic structure.
Prerequisite:
- HTML Basics
- JavaScript Basics
Basically below program will convert a title into a URL Slug using JavaScript.
Approach:
- Create an HTML form with input for the title and output for the URL slug with unique ids.
- Add some CSS style to the element.
- Here, we have used the replace() function in JavaScript to make a string slug.
- The created slug string can be further used in URLs.
Example: Below is the basic HTML code implementation:
Javascript
| functionmyFunction() {    const a = document.getElementById("slug-source").value;    const b = a.toLowerCase().replace(/ /g, '-')        .replace(/[^\w-]+/g, '');    document.getElementById("slug-target").value = b;    document.getElementById("slug-target-span").innerHTML = b;} | 
HTML
| <!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>        <fieldsetclass="slugify">            <legend>                  zambiatek              </legend>            <labelfor="slug-source">                  Input Title:               </label>            <inputtype="text"value=""                   id="slug-source"/>            <labelfor="slug-target">                  URL Slug:               </label>            <inputtype="text"value=""                   id="slug-target"/>            <buttontype="button"                    onClick="myFunction()">                Convert            </button>            <p>                <spanclass="slug-output">                    Generated URL Slug                </span>:                <spanid="slug-target-span"></span>            </p>        </fieldset>    </form></body></html> | 
Output: Click here to check the live Output.
 
				 
					


