我有一个PHP函数,可以将URL转换为SEO友好的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;
}
我知道SEO在javascript中对URL进行此操作毫无意义,但为了保持一致性,我希望URL在我的应用程序中显示相同。有没有人在JavaScript中有功能方便? :]
答案 0 :(得分:11)
看看这个javascript模块(我是作者),在浏览器和server / nodejs中工作 http://pid.github.io/speakingurl/
希望这会有所帮助
答案 1 :(得分:5)
将不同的解决方案放在一起,请考虑这个替代代码,一个单行:
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
}
答案 2 :(得分:4)
var url ="Evanston, IN 47531, USA pizza food & wine & music";
document.write(ToSeoUrl(url));
function ToSeoUrl(url) {
// make the url lowercase
var encodedUrl = url.toString().toLowerCase();
// replace & with and
encodedUrl = encodedUrl.split(/\&+/).join("-and-")
// remove invalid characters
encodedUrl = encodedUrl.split(/[^a-z0-9]/).join("-");
// remove duplicates
encodedUrl = encodedUrl.split(/-+/).join("-");
// trim leading & trailing characters
encodedUrl = encodedUrl.trim('-');
return encodedUrl;
}