Last Updated: December 26, 2018
·
2.269K
· khay

Convert A Title Into Url Slug

This is a trick. Convert the title to lowercase, and replace the spaces with hyphens. For example, Ahri, the Nine-Tailed Fox to ahri-the-nine-tailed-fox.

$("#title").keyup(function(){
    var Text = $(this).val();
    Text = Text.toLowerCase();
    Text = Text.replace(/[^a-zA-Z0-9]+/g,'-');
    $("#slug").val(Text);        
});

1 Response
Add your response

You're missing special chars here. The title "Der süße Vogel isst Flöhe" would become der-s-e-vogel-isst-fl-he. You could omit special chars in general with something like this: encodeURIComponent('<some string>'.replace(/\s+/g, '-')).replace(/\%.{2}/g, ''), but actually the best solution is to replace every special char with an appropriate ASCII equivalent, like: '…'.replace(/ä/ig, 'ae').

Additionally you could use this.value instead of $(this).val(). There' no need to instantiate a jQuery-object.

over 1 year ago ·