I've been doing field validation that should allow a-z characters, spaces, hyphens and periods. The regex is:
/^[a-zA-Z-. ] $/
For the most part, the following works; however, it fails if either -
or .
are repeated:
String
= true,
Str- in.g
= true,
String--
= false,
String...
= false
I know that in some cases, the -
and .
should be escaped but I don't believe they need to be in this case as they are within the [ ].
CodePudding user response:
It returns true for all the strings, what have you tried that's returning false for matching
let reg = /^[a-zA-Z-. ] $/
let tests = ["String", "Str- in.g", "String--", "String...", "String...---str.ing---"]
tests.forEach((item) => {
console.log(`${item} : ${reg.test(item)}`)
})
CodePudding user response:
From docs at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Character_Classes:
A character class. Matches any one of the enclosed characters. You can specify a range of characters by using a hyphen, but if the hyphen appears as the first or last character enclosed in the square brackets, it is taken as a literal hyphen to be included in the character class as a normal character.
That is, if you use the hyphen not at the beginning or end, or as a range delimiter, it is in an undefined state, and depending on the regex implementation it will do one thing or another. So, unless in a range, always put the hyphen at the beginning or end, or \-
escape it.
Fixed regex with tests:
[ 'String', 'Str- in.g', 'String--', 'String...', 'Not good!' ]
.forEach(str => {
let match = /^[a-zA-Z. -] $/.test(str);
console.log(str, '==>', match);
});
Output:
String ==> true
Str- in.g ==> true
String-- ==> true
String... ==> true
Not good! ==> false