In this article. You’ll learn how to check whether a string does not start with a regex in javascript. We use the test()
function to check whether a string does not start with a regex.
Make sure your regular expression starts with a caret (^
), which is a special character that represents the start of the string.
The test()
function will search the string and return true
if the string contains a match otherwise, it returns false
.
let valid = !/^D/.test("Doesn't start with this string.");
console.log(valid);
//When String Starts with D, it returns false
// Output ==> false
valid = !/^D/.test("Mary had a little lamb");
console.log(valid);
//When String Starts not with D, it returns true
// Output ==> true
Another approach is to use [^D]
. Square ([]
) bracket denotes a set of characters to match, and caret (^
) at the start of the set negates the set. So [^D]
matches any character other than D
.
let valid = /^[^D]/.test("Doesn't start with this string.");
console.log(valid);
//When String Starts with D, it returns false
// Output ==> false
valid = /^[^D]/.test("Mary had a little lamb");
console.log(valid);
//When String Starts not with D, it returns true
// Output ==> true
I hope this article will help you to understand how to check whether a string does not start with a regex in javascript.
Share your valuable feedback, please post your comment at the bottom of this article. Thank you!
Comments