JavaScript clean-URL from page Title field
javascript, php, regex, short-url
Solution
All in one go:
var string = "The new page's future name!"
, clean = string.replace(/(^\-+|[^a-zA-Z0-9\/_| -]+|\-+$)/g, '')
.toLowerCase()
.replace(/[\/_| -]+/g, '-')
;
console.log(clean); // "the-new-pages-future-name"
The first `replace` takes care of all unwanted characters AND trims all extra dashes at start and end. The second replace replaces all (groups of) slashes, underscores, pipes and spaces by a hyphen.
Problem
I have a field in my form in which I provide the name of my new page which I'm adding to my CMS. I have a PHP code here which lowers case, sets '-' instead of ' ', and makes a short URL look nice: ``` $clean = iconv('UTF-8', 'ASCII//TRANSLIT', $string); $clean = preg_replace("/[^a-zA-Z0-9\/_| -]/", '', $clean); $clean = strtolower(trim($clean, '-')); $clean = preg_replace("/[\/_| -]+/", '-', $clean); ``` I am NOT EXPERIENCED with JavaScript's RegEx, so can anyone help me convert this piece of PHP code to JavaScript. Thank you all!