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];
};
Use regex replacement:
let forbiddenCharacters = new RegExp("[^a-zA-Z0-9\\s-_]", "g");
return str.replace(forbiddenCharacters, "");
You can use the string replace function with RegEx. Inside the parentheses you declare the characters that you want to allow a-z A-Z 0-9 - and _. The /g stands for global and is used so that the replace won't stop at the first replaced character.
let testString = '!@#$%^&*()+_- 33252qweqreteEWUJHGFA';
let resultString = testString.replace(/[^a-zA-Z0-9-_ ]/g, '');
console.log(resultString);