How to Check Whether a String Does Not Start With a Regex in JavaScript
Dec 29, 2021
To check if a string does not start with specific characters using a regular expression, use the test()
function and negate it.
Make sure your regular expression starts with ^
, which is a special character that represents the start of the string.
function doesNotStartWithA(str) {
return !/^A/.test(str);
}
Another approach is to use [^A]
.
[]
denotes a set of characters to match, and ^
at the start of the set negates the set.
So [^A]
matches any character other than A
.
function doesNotStartWithA(str) {
return /^[^A]/.test(str);
}
More Fundamentals Tutorials
- Convert a Set to an Array in JavaScript
- What Does Setting the Length of a JavaScript Array Do?
- Get the Last Element in an Array in JavaScript
- Skip an Index in JavaScript Array map()
- Conditionally Add an Object to an Array in JavaScript
- Validate Emails using Regex in JavaScript
- JavaScript Copy to Clipboard