Movatterモバイル変換


[0]ホーム

URL:


CodeQL documentation
CodeQL resources

Regular expression always matches

ID: js/regex/always-matchesKind: problemSecurity severity: Severity: warningPrecision: highTags:   - quality   - reliability   - correctness   - regular-expressionsQuery suites:   - javascript-security-and-quality.qls

Click to see the query in the CodeQL repository

There are several built-in JavaScript functions that search for a regular expression match within a string, such asRegExp.prototype.test andString.prototype.search. If the regular expression is not anchored, it only needs to match a substring of the input and won’t necessarily match the whole string.

If the regular expression being searched for accepts the empty string, this means it can match an empty substring anywhere in the input string, and will thus always find a match. In this case, testing if a match exists is redundant and indicates dead code.

Recommendation

Examine the regular expression and determine how it was intended to match:

  • To match the whole input string, add anchors at the beginning and end of the regular expression.

  • To search for an occurrence within the input string, consider what the shortest meaningful match is and restrict the regular expression accordingly, such as by changing a* to a+.

Example

In the following example, a regular expression is used to check the format of a stringid. However, the check always passes because the regular expression can match the empty substring. For example, it will allow the ID string “%%” by matching an empty string at index 0.

if(!/[a-z0-9]*/.test(id)){thrownewError("Invalid id: "+id);}

To ensure the regular expression matches the whole string, add anchors at the beginning and end:

if(!/^[a-z0-9]*$/.test(id)){thrownewError("Invalid id: "+id);}

References


[8]ページ先頭

©2009-2025 Movatter.jp