0

How to Check Whether a String Does Not Start With a Regex in JavaScript

 2 years ago
source link: https://masteringjs.io/tutorials/fundamentals/regex-not-starting-with
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK