Skip to content

Instantly share code, notes, and snippets.

@jlucasps
Last active December 13, 2015 18:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jlucasps/4958118 to your computer and use it in GitHub Desktop.
Save jlucasps/4958118 to your computer and use it in GitHub Desktop.
Transforms String in URL
// Transforms String in URL
function friendly_url(str, max) {
if (max === undefined) max = 32;
var a_chars = new Array(
new Array("a", /[áàâãªÁÀÂÃŪ]/g),
new Array("e", /[éèêÉÈÊ]/g),
new Array("i", /[íìîÍÌÎ]/g),
new Array("o", /[òóôõºÓÒÔÕ°Ö]/g),
new Array("u", /[úùûÚÙÛµÜü]/g),
new Array("c", /[çÇ¢©]/g),
new Array("d", /[Ð]/g),
new Array("n", /[Ññ]/g),
new Array("s", /[Šš§]/g),
new Array("z", /[Žž]/g),
new Array("y", /[Ÿ¥Ýýÿ]/g),
new Array("ae", /[Æœæ]/g),
new Array("ce", /[Œ]/g),
new Array("r", /[®]/g),
new Array("0", /[º]/g),
new Array("1", /[¹]/g),
new Array("2", /[²]/g),
new Array("3", /[³]/g)
);
// Replace vowel with accent without them
for (var i = 0; i < a_chars.length; i++) {
str = str.replace(a_chars[i][1], a_chars[i][0]);
}
/* first replace whitespace by -, second remove repeated - by just one, third turn in low case the chars,
* fourth delete all chars which are not between a-z or 0-9, fifth trim the string and
* the last step truncate the string to 32 chars
*/
return str.replace(/\s+/g, '-').toLowerCase().replace(/[^a-z0-9\-]/g, '').replace(/\-{2,}/g, '-').replace(/(^\s*)|(\s*$)/g, '').substr(0, max);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment