Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Producing SEO friendly URL in javascript

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? :]

like image 255
el_pup_le Avatar asked Jan 01 '13 02:01

el_pup_le


2 Answers

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
}
like image 52
Dan Barto Avatar answered Sep 30 '22 18:09

Dan Barto


Take a look at this Javascript module (I'm the author), which works in browser and server/nodejs:
SpeakingURL

like image 42
pid Avatar answered Sep 30 '22 18:09

pid