Search code examples
javascriptdjangoreplaceall

How to remove all symbols within a given string in Javascript?


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("'", "")
      };