Home > Software design >  How to remove all symbols within a given string in Javascript?
How to remove all symbols within a given string in Javascript?

Time:02-22

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!

CodePudding user response:

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

CodePudding user response:

Something like this?

let stringToReplace = '12 3B()S$%\|#s'
let desired = stringToReplace.replace(/[^\w\s]/gi, '')

The (^) character is the negation of whatever comes in the set [...],

gi stands for: global and case-insensitive

Plus we put a safelist in there:

In our case digits, chars, underscores (\w) whitespace (\s).

So whatever is out of our whitelist gots replaced with ''

  • Related