Search the blog

Creating a SEO-friendly CMS is a must nowadays. This neat little JQuery function will allow the user to type anything into a URL/slug field and then on focus/blur it will parse the text and convert it to a “pretty” URL.

$('input.slug').on('focus blur', function() {

    var string              = $(this).val();
    var strReplaceAll       = string;
    var intIndexOfMatch     = strReplaceAll.indexOf(' ');

    while(intIndexOfMatch != -1){

        strReplaceAll       = strReplaceAll.replace(' ', '-');
        intIndexOfMatch     = strReplaceAll.indexOf(' ');

    }

    string = strReplaceAll;

    for(var i = 0, output = '', valid='-0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; i < string.length; i++) {

        if(valid.indexOf(string.charAt(i)) != -1) {

            output += string.charAt(i);

        }

    }

    $(this).val(output.toLowerCase());

});
Tim Bennett is a web designer and developer. He has a First Class Honours degree in Computing from Leeds Metropolitan University and currently runs his own one-man web design company, Texelate.