Last Updated: February 25, 2016
·
1.109K
· merianos

jQuery | string slugify

Ok, I am creating a project that allowing the end user to enter the sub-domain of his profile in my app, and I like to filter out what this user enters, in order to prevent insertion of special and/or Greek characters (as the application is dedicated to greek users).

The code I builded out, that filtering out what's in the sub-domain is the following:

$('SELECTOR_HERE').on(
    'keyup',
    function(e)
    {
        var current_cursor_location =   this.selectionStart;

        var str =   $(this).val();

        str     =   str.replace(/^\s+|\s+$/g, ''); // trim
        str     =   str.toLowerCase();

        // Replace with your special alphabet
        var from = "αάσδφγηήξκλζχώωβνμςεέρτύυϋΰιίϊΐοόπ·/_,:;";
        var to   = "aasdfgiixklzxoovnmseertiiiiiiiioop------";

        for(var i = 0, l = from.length ; i < l ; i++)
        {
            str = str.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i));
        }

        // Replacing special letters with double english letters
        str     =   str.replace(new RegExp('ψ', 'g'), 'ps');
        str     =   str.replace(new RegExp('θ', 'g'), 'th');

        str = str.replace(/[^a-z0-9 -]/g, '')   //  remove invalid chars
            .replace(/\s+/g, '-')               //  collapse whitespace and replace by -
            .replace(/-+/g, '-');               //  collapse dashes

        $(this).val(str);

        if(current_cursor_location > str.length)
        {
            this.setSelectionRange(str.length, str.length);
        }
        else
        {
            this.setSelectionRange(current_cursor_location, current_cursor_location);
        }
    }
);