Issue
Currently I am using the following Javascript code to convert a product title into URL-slug within the base template of my django project.
document.getElementById("title").onkeyup = function () {
document.getElementById("url_slug").value = document
.getElementById("title")
.value.toLowerCase()
.replaceAll(" ", "-")
.replaceAll("'", "")
};
This is using consecutive replaceAll() methods to replace space with dash then remove apostrophes but i would like to prevent all other symbols (e.g. +=()[]$%@#... etc) as well.
Surely there must be a better way? Thanks in advance for any suggestions!
Solution
You can remove all characters with regex expression /[^A-Za-z0-9]/g
document.getElementById("title").onkeyup = function () {
document.getElementById("url_slug").value = document
.getElementById("title")
.value.toLowerCase().replace(/[^A-Za-z0-9]/g,'')
.replaceAll(" ", "-")
.replaceAll("'", "")
};
Answered By - Wasif Ali
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.