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

Add prefer-replace-all rule #488

Merged
merged 20 commits into from Feb 1, 2020
Merged
Show file tree
Hide file tree
Changes from 10 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
24 changes: 24 additions & 0 deletions docs/rules/prefer-replace-all.md
@@ -0,0 +1,24 @@
# Prefer `String.prototype.replaceAll` over regex searches with the global flag.

As the replaceAll method is being added to strings, there is no reason to use expensive regex searches when the search string is a string-literal.

This rule is fixable.


## Fail

```js
str.replace(/This has no special regex symbols/g, 'something');
str.replace(/\(It also checks for escaped regex symbols\)/g, 'something');

```


## Pass

```js
str.replace(/Non-literal characters .*/g, 'something');
str.replace(/Extra flags/gi, 'something');
str.replace('Not a regex expression', 'something')
str.replaceAll('literal characters only', 'something');
```
1 change: 1 addition & 0 deletions index.js
Expand Up @@ -55,6 +55,7 @@ module.exports = {
'unicorn/prefer-node-remove': 'error',
'unicorn/prefer-query-selector': 'error',
'unicorn/prefer-reflect-apply': 'error',
'unicorn/prefer-replace-all': 'off',
'unicorn/prefer-spread': 'error',
'unicorn/prefer-starts-ends-with': 'error',
'unicorn/prefer-string-slice': 'error',
Expand Down
2 changes: 2 additions & 0 deletions readme.md
Expand Up @@ -73,6 +73,7 @@ Configure it in `package.json`.
"unicorn/prefer-node-remove": "error",
"unicorn/prefer-query-selector": "error",
"unicorn/prefer-reflect-apply": "error",
"unicorn/prefer-replace-all": "off",
"unicorn/prefer-spread": "error",
"unicorn/prefer-starts-ends-with": "error",
"unicorn/prefer-string-slice": "error",
Expand Down Expand Up @@ -127,6 +128,7 @@ Configure it in `package.json`.
- [prefer-node-remove](docs/rules/prefer-node-remove.md) - Prefer `node.remove()` over `parentNode.removeChild(node)` and `parentElement.removeChild(node)`. *(fixable)*
- [prefer-query-selector](docs/rules/prefer-query-selector.md) - Prefer `.querySelector()` over `.getElementById()`, `.querySelectorAll()` over `.getElementsByClassName()` and `.getElementsByTagName()`. *(partly fixable)*
- [prefer-reflect-apply](docs/rules/prefer-reflect-apply.md) - Prefer `Reflect.apply()` over `Function#apply()`. *(fixable)*
- [prefer-replace-all](docs/rules/prefer-replace-all.md) - Prefer `String.prototype.replaceAll` over regex searches with the global flag. *(fixable)*
- [prefer-spread](docs/rules/prefer-spread.md) - Prefer the spread operator over `Array.from()`. *(fixable)*
- [prefer-starts-ends-with](docs/rules/prefer-starts-ends-with.md) - Prefer `String#startsWith()` & `String#endsWith()` over more complex alternatives.
- [prefer-string-slice](docs/rules/prefer-string-slice.md) - Prefer `String#slice()` over `String#substr()` and `String#substring()`. *(partly fixable)*
Expand Down
56 changes: 56 additions & 0 deletions rules/prefer-replace-all.js
@@ -0,0 +1,56 @@
'use strict';
const getDocumentationUrl = require('./utils/get-documentation-url');
const quoteString = require('./utils/quote-string');

function isRegexWithGlobalFlag(node) {
const {type, regex} = node;

return type === 'Literal' && regex && regex.flags === 'g';
}

function isLiteralCharactersOnly(node) {
const searchPattern = node.regex.pattern;
const specialCharacters = searchPattern.match(/[$()*+.?[\\\]^{}]/g);
const specialCharactersCount = specialCharacters ? specialCharacters.length : 0;
const escapedSpecialCharacters = searchPattern.match(/\\[$()*+.?[\\\]^{}]/g);
const escapedSpecialCharactersCount = escapedSpecialCharacters ? escapedSpecialCharacters.length : 0;
return specialCharactersCount === 2 * escapedSpecialCharactersCount;
}
fisker marked this conversation as resolved.
Show resolved Hide resolved

const create = context => {
return {
'CallExpression[callee.property.name="replace"]': node => {
const {arguments: arguments_} = node;

if (arguments_.length !== 2) {
return;
}

const [search] = arguments_;

if (!isRegexWithGlobalFlag(search) || !isLiteralCharactersOnly(search)) {
return;
}

context.report({
node,
message: 'Use replaceAll method of string.',
jmoore914 marked this conversation as resolved.
Show resolved Hide resolved
fix: fixer => [
fixer.insertTextAfter(node.callee, 'All'),
fixer.replaceText(search, quoteString(search.regex.pattern))
]
});
}
};
};

module.exports = {
create,
meta: {
type: 'suggestion',
docs: {
url: getDocumentationUrl(__filename)
},
fixable: 'code'
}
};
87 changes: 87 additions & 0 deletions test/prefer-replace-all.js
@@ -0,0 +1,87 @@
import test from 'ava';
import avaRuleTester from 'eslint-ava-rule-tester';
const rule = require('../rules/prefer-replace-all');

//------------------------------------------------------------------------------
// Tests
//------------------------------------------------------------------------------

const ruleTester = avaRuleTester(test, {
env: {
es6: true
}
});

const error = {
ruleId: 'prefer-replace-all',
message: 'Use replaceAll method of string.'
};

ruleTester.run('prefer-replace-all', rule, {
valid: [
// No global flag
'foo.replace(/a/, bar)',
// Special characters
'foo.replace(/[a]/g, bar)',
'foo.replace(/a?/g, bar)',
'foo.replace(/.*/g, bar)',
'foo.replace(/\\W/g, bar)',
// Extra flag
'foo.replace(/a/gi, bar)',
// Not regex literal
'foo.replace(\'string\', bar)',
// Not 2 arguments
'foo.replace(/a/g)',
// New
'new foo.replace(/a/g, bar)',
// Function call
'replace(/a/g, bar)',
// Not call
'foo.replace',
// Not replace
'foo.methodNotReplace(/a/g, bar);',
// `replace` is not Identifier
'foo[\'replace\'](/a/gi, bar)'
],
invalid: [
{
code: 'foo.replace(/a/g, bar)',
output: 'foo.replaceAll(\'a\', bar)',
errors: [error]
},
// Comments
{
code: `
foo/* comment 1 */
.replace/* comment 2 */(
/* comment 3 */
/a/g // comment 4
,
bar
)
`,
output: `
foo/* comment 1 */
.replaceAll/* comment 2 */(
/* comment 3 */
'a' // comment 4
,
bar
)
`,
errors: [error]
},
// Quotes
{
code: 'foo.replace(/"\'/g, \'\\\'\')',
output: 'foo.replaceAll(\'"\\\'\', \'\\\'\')',
errors: [error]
},
// Escaped symbols
{
code: 'foo.replace(/\\./g, bar)',
output: 'foo.replaceAll(\'.\', bar)',
errors: [error]
},
]
});