DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Javascript Normalize - Removes Accents And Others Invalid Chars.

01.23.2011
| 6804 views |
  • submit to reddit
        // this snippet is useful for making urls slugs, or comparing user inputs to a normalized string.

    var normalize = (function() {
        var from = "ÃÀÁÄÂÈÉËÊÌÍÏÎÒÓÖÔÙÚÜÛãàáäâèéëêìíïîòóöôùúüûÑñÇç", 
            to   = "AAAAAEEEEIIIIOOOOUUUUaaaaaeeeeiiiioooouuuunncc",
            mapping = {};
        
        for(var i=0; i<from.length; i++)
            mapping[from.charAt(i)] = to.charAt(i);
        
        return function(str) {
            var ret = []
            for(var i=0; i<str.length; i++) {
                var c = str.charAt(i)
                if(mapping.hasOwnProperty(str.charAt(i)))
                    ret.push(mapping[c]);
                else
                    ret.push(c);
            }
            return ret.join('').replace(/[^-A-Za-z0-9]+/g, '-').toLowerCase();
        }

    })();