Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: no-regex-spaces support v flag #17407

Merged
merged 3 commits into from Jul 25, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
21 changes: 18 additions & 3 deletions lib/rules/no-regex-spaces.js
Expand Up @@ -77,7 +77,7 @@ module.exports = {
let regExpAST;

try {
regExpAST = regExpParser.parsePattern(pattern, 0, pattern.length, flags.includes("u"));
regExpAST = regExpParser.parsePattern(pattern, 0, pattern.length, { unicode: flags.includes("u"), unicodeSets: flags.includes("v") });
} catch {

// Ignore regular expressions with syntax errors
Expand Down Expand Up @@ -155,13 +155,28 @@ module.exports = {
const regExpVar = astUtils.getVariableByName(scope, "RegExp");
const shadowed = regExpVar && regExpVar.defs.length > 0;
const patternNode = node.arguments[0];
const flagsNode = node.arguments[1];

if (node.callee.type === "Identifier" && node.callee.name === "RegExp" && isString(patternNode) && !shadowed) {
const pattern = patternNode.value;
const rawPattern = patternNode.raw.slice(1, -1);
const rawPatternStartRange = patternNode.range[0] + 1;
const flags = isString(flagsNode) ? flagsNode.value : "";
let flags;

if (node.arguments.length < 2) {

// It has no flags.
flags = "";
} else {
const flagsNode = node.arguments[1];

if (isString(flagsNode)) {
flags = flagsNode.value;
} else {

// The flags cannot be determined.
return;
}
}

checkRegex(
node,
Expand Down
21 changes: 20 additions & 1 deletion tests/lib/rules/no-regex-spaces.js
Expand Up @@ -62,9 +62,15 @@ ruleTester.run("no-regex-spaces", rule, {
"var foo = new RegExp(' \\[ ');",
"var foo = new RegExp(' \\[ \\] ');",

// ES2024
{ code: "var foo = / {2}/v;", parserOptions: { ecmaVersion: 2024 } },
{ code: "var foo = /[\\q{ }]/v;", parserOptions: { ecmaVersion: 2024 } },

// don't report invalid regex
"var foo = new RegExp('[ ');",
"var foo = new RegExp('{ ', 'u');"
"var foo = new RegExp('{ ', 'u');",
"new RegExp('[[abc] ]', flags + 'v')",
ota-meshi marked this conversation as resolved.
Show resolved Hide resolved
"new RegExp('[[abc]\\\\q{ }]', flags + 'v')"
],

invalid: [
Expand Down Expand Up @@ -371,6 +377,19 @@ ruleTester.run("no-regex-spaces", rule, {
type: "NewExpression"
}
]
},

// ES2024
ota-meshi marked this conversation as resolved.
Show resolved Hide resolved
{
code: "var foo = new RegExp('[[ ] ] ', 'v');",
output: "var foo = new RegExp('[[ ] ] {4}', 'v');",
errors: [
{
messageId: "multipleSpaces",
data: { length: "4" },
type: "NewExpression"
}
]
}
]
});