String.prototype.slugify = function(){
return this.replace('ø','oe').replace('å','aa').replace(/\W/gi,'_').replace(/_+/g,'_');
}
var x = 'sdfkjshødfjsåkdhf#@$%#$Tdkfsdfxzhfjkasd23hj4rlsdf9';
x.slugify();
Add as many rules as you'd like following the .replace('search','replace')
pattern. Make sure that you finish it with .replace(/\W/gi,'_').replace(/_+/,'_')
, which converts . Also ensure you serve it up in UTF-8 to accommodate the special characters like ø.
An alternate version, suggested by Strager:
String.prototype.slugify = function(){
var replacements = {
'ø': 'oe',
'å': 'aa'
}
var ret = this;
for(key in replacements) ret = ret.replace(key, replacements[key]);
return ret.replace(/\W/gi,'_').replace(/_+/g,'_');
}
This version is certainly more flexible and maintainable. I'd use this one, though I'm keeping the previous iteration for posterity. Great idea, Strager!