I have a PHP function that converts a URL to an SEO friendly URL:
function seo_url($input){
$input = str_replace(array("'", "-"), "", $input); //remove single quote and dash
$input = mb_convert_case($input, MB_CASE_LOWER, "UTF-8"); //convert to lowercase
$input = preg_replace("#[^a-zA-Z0-9]+#", "-", $input); //replace everything non an with dashes
$input = preg_replace("#(-){2,}#", "$1", $input); //replace multiple dashes with one
$input = trim($input, "-"); //trim dashes from beginning and end of string if any
return $input;
}
I know it's pointless for SEO to do this to a URL in javascript, but for the sake of consistency I want URL's to appear the same in my application. Does anyone have the function handy in javascript? :]
Getting pieces of different solutions together, please consider this alternative code, a one-liner:
function toSeoUrl(url) {
return url.toString() // Convert to string
.normalize('NFD') // Change diacritics
.replace(/[\u0300-\u036f]/g,'') // Remove illegal characters
.replace(/\s+/g,'-') // Change whitespace to dashes
.toLowerCase() // Change to lowercase
.replace(/&/g,'-and-') // Replace ampersand
.replace(/[^a-z0-9\-]/g,'') // Remove anything that is not a letter, number or dash
.replace(/-+/g,'-') // Remove duplicate dashes
.replace(/^-*/,'') // Remove starting dashes
.replace(/-*$/,''); // Remove trailing dashes
}
Take a look at this Javascript module (I'm the author), which works in browser and server/nodejs:
SpeakingURL
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With