ParisNakitaKejser
ParisNakitaKejser

Reputation: 14841

Escaping special characters in JavaScript

I need a method in JavaScript to escape all characters which are not ( a-z / A-Z / 0-9 / - / _ )

If the character is ø it should be replaced with oe, if it's å then replaced with aa, and more.... if characters are not on the list, they should be replaced with an underscore.

If there are 2 underscores in a row ( __ ) they should be replaced with a single underscore.

I need this done in JavaScript and/or PHP.

Upvotes: 1

Views: 1053

Answers (1)

c_harm
c_harm

Reputation:

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!

Upvotes: 6

Related Questions