Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading