tanvi
tanvi

Reputation: 628

Regex to remove special characters from a string

I'm trying to write a regex that only allows letters, numbers, single white spaces, '-' literal, and '/' literal. How do I limit my expression to only these?

If I enter "This should be invalid because it ends with!!! these", it is still returned as a valid string, even though there's an exclamation at the end.
The one I have is not entirely correct:

[A-Z]|[a-z]|[0-9]|/|\s|-

Upvotes: 0

Views: 338

Answers (1)

gyre
gyre

Reputation: 16777

The problem here is that, by default, regular expressions do not have to match the entire string. One character is sufficient to constitute a match (and sometimes even none)! You need to surround your regex like ^(?: ... )+$ to make it work as you want:

console.log([
    'This should be invalid because it ends with!!! these', //=> false
    'This is valid' //=> true
].map(/ /.test,
  /^(?:[A-Z]|[a-z]|[0-9]|\/|\s|-)+$/
))

However, a more compact way to write the same expression would be ^[A-Za-z\d\s\/-]+$.

console.log([
    'This should be invalid because it ends with!!! these', //=> false
    'This is valid' //=> true
].map(/ /.test,
  /^[A-Za-z\d\s\/-]+$/
))

Upvotes: 1

Related Questions