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);
});Written by K
Related protips
1 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.
Have a fresh tip? Share with Coderwall community!
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