ThemePackNet

Slug from title with pure JS

Jan 21st, 2021 (edited)
85
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Title filed
  2. <input name="title" type="text" class="form-control" placeholder="Enter title" onload="convertToSlug(this.value)" onkeyup="convertToSlug(this.value)">
  3.  
  4. Slug field
  5. <input name="slug" type="text" class="form-control" id="slug-text" placeholder="web-developer">
  6.  
  7. Script
  8. <script>
  9.     function convertToSlug(str) {
  10.         //replace all special characters | symbols with a space
  11.         str = str.replace(/[`~!@#$%^&*()_\-+=\[\]{};:'"\\|\/,.<>?\s]/g, ' ').toLowerCase();
  12.  
  13.         // trim spaces at start and end of string
  14.         str = str.replace(/^\s+|\s+$/gm, '');
  15.  
  16.         // replace space with dash/hyphen
  17.         str = str.replace(/\s+/g, '-');
  18.  
  19.         //return str;
  20.         document.getElementById("slug-text").value = str;
  21.     }
  22. </script>
  23.  
RAW Paste Data