Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Match any single character outside the given set.
To match any single character outside the given set with JavaScript RegExp, use the [^...] metacharacter. The caret ^ inside square brackets creates a negated character class that matches any character NOT in the specified set.
Syntax
/[^characters]/flags
Where characters are the characters you want to exclude from matching.
Example: Matching Characters Outside a Set
<html>
<head>
<title>JavaScript Regular Expression</title>
</head>
<body>
<script>
var myStr = "Welcome!";
var reg = /[^lc]/g;
var match = myStr.match(reg);
document.write("Original string: " + myStr + "<br>");
document.write("Pattern [^lc]: " + reg + "<br>");
document.write("Matches: " + match);
</script>
</body>
</html>
Original string: Welcome! Pattern [^lc]: /[^lc]/g Matches: W,e,o,m,e,!
Common Use Cases
<html>
<head>
<title>RegExp Negated Character Sets</title>
</head>
<body>
<script>
// Match non-vowels
var text1 = "Hello World";
var nonVowels = text1.match(/[^aeiouAEIOU]/g);
document.write("Non-vowels: " + nonVowels + "<br>");
// Match non-digits
var text2 = "Price: $25.99";
var nonDigits = text2.match(/[^0-9]/g);
document.write("Non-digits: " + nonDigits + "<br>");
// Match characters excluding spaces and punctuation
var text3 = "Hi, how are you?";
var letters = text3.match(/[^, ?!]/g);
document.write("Letters only: " + letters);
</script>
</body>
</html>
Non-vowels: H,l,l, ,W,r,l,d Non-digits: P,r,i,c,e,:, ,$,., Letters only: H,i,h,o,w,a,r,e,y,o,u
Key Points
- The
^symbol inside[]negates the character set - It matches any single character NOT listed in the brackets
- Use the
gflag to find all matches, not just the first one - Ranges like
[^a-z]exclude all lowercase letters
Conclusion
The negated character class [^...] is essential for matching characters outside a specific set. It's particularly useful for filtering out unwanted characters or validating input formats.
Advertisements
