Last Updated : 05 Aug, 2025
The [^abc] expression in JavaScript regular expressions is a negated character set. It matches any character except those specified inside the brackets. For example, [^abc] matches any character that is not a, b, or c.
JavaScript
let regex = /[^abc]/g;
let str = "abcdefg";
let matches = str.match(regex);
console.log(matches);
[ 'd', 'e', 'f', 'g' ]
The pattern [^abc] excludes a, b, and c, matching only d, e, f, and g.
Syntax:/[^characters]/
let regex = /[^aeiou]/g;
// Matches all non-vowel characters
let str = "hello world";
let matches = str.match(regex);
console.log(matches);
[ 'h', 'l', 'l', ' ', 'w', 'r', 'l', 'd' ]
Here, [^aeiou] matches any character that is not a vowel.
2. Excluding Specific Digits JavaScript
let regex = /[^123]/g;
let str = "123456789";
let matches = str.match(regex);
console.log(matches);
[ '4', '5', '6', '7', '8', '9' ]
The pattern [^123] excludes the digits 1, 2, and 3, matching the remaining numbers.
3. Filtering Out Specific Characters JavaScript
let regex = /[^a-zA-Z]/g;
// Matches all non-alphabetic characters
let str = "Code123!";
let result = str.replace(regex, "");
console.log(result);
The [^a-zA-Z] pattern removes all characters that are not alphabets.
4. Validating Input JavaScript
let regex = /[^a-zA-Z0-9]/;
let username = "User_123";
if (regex.test(username)) {
console.log("Invalid username. Contains special characters.");
} else {
console.log("Valid username.");
}
Invalid username. Contains special characters.
The [^a-zA-Z0-9] pattern detects any special character in the username.
5. Excluding Ranges JavaScript
let regex = /[^0-9]/g;
// Matches all non-digit characters
let str = "abc123xyz";
let matches = str.match(regex);
console.log(matches);
[ 'a', 'b', 'c', 'x', 'y', 'z' ]
Here, [^0-9] matches any character that is not a digit.
Common Patterns Using [^...]/[^0-9]/g
/[^a-zA-Z]/g
/[^\s]/g
/[^abc]/gWhy Use [^...]?
The [^abc] expression is a powerful way to define what not to match, making it a critical tool for complex string processing and validation tasks in JavaScript.
Recommended Links:RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4