This can be done easily using Regular expressions.

Following is the sequence of steps to be done:

  1. Step 1 is to convert the entire string to a lowercase letter. Although URLs are case insensitive, it looks good if the entire string has lowercase letters.
  2. Step 2 is to remove characters from the title other than alphanumeric and space.
  3. Step3 is to replace a space with “-“

Let’s write a function in JS that takes a title as an input and returns the URL slug as an output.

<html>
    <head>
      <script>
      	function TitleToSlug(){
          	var Title = document.getElementById("title").value;
    		var output =  Title.toLowerCase();
        	output = output.replace(/[^\w ]+/g, '');
        	output = output.replace(/ +/g, '-');
	        document.getElementById("output").textContent = output;
        
		}	
       </script> 
    </head>
    <body>
    	<input id="title" type="text" placeholder = "enter a title" oninput="TitleToSlug()"/>
        <br>
    	<span id="output">  </span>
    </body>
     
<html>


Categorized in:

Tagged in: