How do I create a function in javascript that only allows letters, numbers, dashes -, underscores _ and spaces?

Advertisements

I have to create a function that takes a string, removes all "special" characters (e.g. !, @, #, $, %, ^, &, , *, (, )) and
returns the new string. The only non-alphanumeric characters allowed are dashes -, underscores _ and spaces.

I’m new at this so I understand that this code may be ALL wrong.

module.exports = (str) => {
let allowedCharacters = [a-zA-Z0-9/s-_];
for (let i = 0; i < str.length; i++) {
    allowedCharacters += str[i]
}
return str[i];
};

>Solution :

Use regex replacement:

let forbiddenCharacters = new RegExp("[^a-zA-Z0-9\\s-_]", "g");
return str.replace(forbiddenCharacters, "");

Leave a ReplyCancel reply