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 do I create a function in javascript that only allows letters, numbers, dashes -, underscores _ and spaces?

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];
};

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 :

Use regex replacement:

let forbiddenCharacters = new RegExp("[^a-zA-Z0-9\\s-_]", "g");
return str.replace(forbiddenCharacters, "");
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