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);
}
}
);Written by Merianos Nikos
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Javascript
Authors
Did you know?
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#