'JS regular expression Allow alphanumeric characters and . , " ( ) - _ # : ; * @ & not remaining +, =, $, !, <, >, `, ~, {, }, |,\,?, ~
i tried with below pattern
var pattern = new RegExp("^[ A-Za-z0-9.,()-_#:;*@&]*$");
console.log(pattern.test("asda ?"));// giving true
but with, i need to get the false. Please provides regExp to allow alphanumeric characters and . , " ( ) - _ # : ; * @ & not remaining special chars +, =, $, !, <, >, `, ~, {, }, |,?, ~
Solution 1:[1]
You could try this:
var pattern = new RegExp(/"^[ A-Za-z0-9.,()-_#:;*@&]*$"/);
console.log(pattern.test("asda ?"));// giving true
this should allow your variable to accept universal characters
Solution 2:[2]
A dash (-) in the middle of a character class ([...]) means interval.A-Z means all characters between and including A and Z.
The same way, )-_ does not mean any of ), - and _ but all characters between ) and _. This range includes digits, uppercase letters and a lot of other characters you want to exclude (+, <, ,>, ? etc). Check the ASCII table to find the complete list.
In order to prevent the dash (-) to have a special meaning in a character class you can put it as the last character in the class.
Use the following fragment of code in your browser to see how the regex matches (or doesn't match) the printable ASCII characters:
let pattern = new RegExp("^[ A-Za-z0-9.,()_#:;*@&-]*$");
for (let i = ' '.charCodeAt(0); i < '~'.charCodeAt(0); i ++) {
console.log(`'${String.fromCharCode(i)}': ${pattern.test(String.fromCharCode(i))}`);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Muhammad Abdullah |
| Solution 2 |
