Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

160
Vistas
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];
};
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Use regex replacement:

let forbiddenCharacters = new RegExp("[^a-zA-Z0-9\\s-_]", "g");
return str.replace(forbiddenCharacters, "");
about 4 years ago · Juan Pablo Isaza Denunciar

0

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);

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda