Skip to content

Commit 013816f

Browse files
authored
Refactor prefer-replace-all with stricter selector (#516)
1 parent bd7a4df commit 013816f

File tree

2 files changed

+20
-13
lines changed

2 files changed

+20
-13
lines changed

rules/prefer-replace-all.js

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,14 @@
11
'use strict';
22
const getDocumentationUrl = require('./utils/get-documentation-url');
33
const quoteString = require('./utils/quote-string');
4+
const methodSelector = require('./utils/method-selector');
5+
6+
const selector = methodSelector({
7+
name: 'replace',
8+
length: 2
9+
});
10+
11+
const message = 'Prefer `String#replaceAll()` over `String#replace()`.';
412

513
function isRegexWithGlobalFlag(node) {
614
const {type, regex} = node;
@@ -29,13 +37,8 @@ function removeEscapeCharacters(regexString) {
2937

3038
const create = context => {
3139
return {
32-
'CallExpression[callee.property.name="replace"]': node => {
40+
[selector]: node => {
3341
const {arguments: arguments_} = node;
34-
35-
if (arguments_.length !== 2) {
36-
return;
37-
}
38-
3942
const [search] = arguments_;
4043

4144
if (!isRegexWithGlobalFlag(search) || !isLiteralCharactersOnly(search)) {
@@ -44,7 +47,7 @@ const create = context => {
4447

4548
context.report({
4649
node,
47-
message: 'Prefer `String#replaceAll()` over `String#replace()`.',
50+
message,
4851
fix: fixer =>
4952
[
5053
fixer.insertTextAfter(node.callee, 'All'),

test/prefer-replace-all.js

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -29,16 +29,20 @@ ruleTester.run('prefer-replace-all', rule, {
2929
// Not 2 arguments
3030
'foo.replace(/a/g)',
3131
'foo.replace(/\\\\./g)',
32-
// New
32+
// Not `CallExpression`
3333
'new foo.replace(/a/g, bar)',
34-
// Function call
34+
// Not `MemberExpression`
3535
'replace(/a/g, bar)',
36-
// Not call
37-
'foo.replace',
36+
// Computed
37+
'foo[replace](/a/g, bar);',
3838
// Not replace
3939
'foo.methodNotReplace(/a/g, bar);',
40-
// `replace` is not Identifier
41-
'foo[\'replace\'](/a/g, bar)'
40+
// `callee.property` is not a `Identifier`
41+
'foo[\'replace\'](/a/g, bar)',
42+
// More or less argument(s)
43+
'foo.replace(/a/g, bar, extra);',
44+
'foo.replace();',
45+
'foo.replace(...argumentsArray, ...argumentsArray2)'
4246
],
4347
invalid: [
4448
{

0 commit comments

Comments
 (0)