Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

165
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda