I have a string from which I want to check if it only contains characters that are allowed. I want only characters of
alphanumeric (lower & upper) : A-Z, a-z
numeric (0-9)
special characters: _&!.-
space
example of valid strings:
- title1 - header
- title2&&& header_!.
- 09
- a912
- ...dd
example of invalid strings
- a$$$ ()
- a12345^&6**
if at least one of characters is not in the special characters so it not valid string. I would like to know how do test it in javascript. the regex patterns come from server so it string. I convert the regex pattern string by using RegExp but all of them show false, even some of them are valid. the three first lines should be valid (true)
const pattern = "^[a-z0-9_&!.-\\s]+$";
const strings = [
`title1 - header`,
`title2&&& header_!.-`,
`09`,
`a912 dd`,
`a$$$ ()`,
`a12345^&6**`
]
const regex = new RegExp(pattern);
strings.forEach(str => {
console.log(str, ' ---> ', regex.test(str));
});
"/^[a-z0-9_&!.-\s]+$/"is not valid input for the RegExp constructor because you shouldn't be passing the/delimiters there. Either change your backend to give you valid regular expressions or pre-process this before feeding it into RegExppatternvariable is wrong here -\shas to be double escaped as\\s. But that's only an issue with the stack snippet. Why do regex constructors need to be double escaped?