here be dragons
here be dragons

Reputation: 13

How do I find special characters in an input string?

const password = document.getElementById('password')

password.addEventListener('input', (e) => {
  let input = e.target.value

  const specialCharacter = "!@#$%^&*()"

  if(input.indexOf(specialCharacter) > -1) {
    console.log('detected special character')
  } else {
    console.log('not special')
  }
})
  <input type="password" id='password' placeholder="Enter Password">

I want the code to know when a special character is typed in, but I can't seem to get why special characters are not detected.

Upvotes: 1

Views: 849

Answers (3)

Adriano
Adriano

Reputation: 3934

You might want to consider using the pattern attribute on the input field to determine what characters are allowed.

This question will be a good starting point, I believe
HTML5 pattern allow specific special characters

Then, you will have to make sure you also have data sanitation in your backend, but I will leave that to you, and for another question :)

Upvotes: 0

user1280483
user1280483

Reputation: 560

You must iterate over all the characters in the specialCharacter string, and do indexOf on each character. This code currently checks if the exact string "!@#$%^&*()" is located in the input. For example:

const password = document.getElementById('password')

password.addEventListener('input', (e) => {
    let input = e.target.value
    ...
    const specialCharacter = "!@#$%^&*()"
    for (var i in specialCharacter) { // Iterate over the string
        if(input.indexOf(specialCharacter[i]) > -1) {
            console.log('detected special character')
        } else {
            console.log('not special')
        }
    }
})

Upvotes: 1

Anthony Oyathelemhi
Anthony Oyathelemhi

Reputation: 14

You are attempting to search for the entire sequence of special characters in input, but what you should be doing is check if ANY of the special characters is present within input

You should probably do this using Regex

const password = document.getElementById('password')

password.addEventListener('input', (e) => {
  let input = e.target.value

  const specialCharacterRegex = /[!@#$%^&*()]+/

  if(specialCharacterRegex.test(input)) {
    console.log('detected special character')
  } else {
    console.log('not special')
  }
})

Upvotes: 0

Related Questions