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 5 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
53 changes: 53 additions & 0 deletions rules/prefer-replace-all.js
@@ -0,0 +1,53 @@
'use strict';
const getDocumentationUrl = require('./utils/get-documentation-url');
const quoteString = require('./utils/quote-string');

function hasGlobalFlag(node) {
const searchPattern = node.arguments[0];
return searchPattern && searchPattern.regex && searchPattern.regex.flags === 'g';
}

function isLiteralCharactersOnly(node) {
const searchPattern = node.arguments[0].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;
}

function replaceNode(node, fixer) {
const stringName = node.callee.object.name;
const searchPattern = node.arguments[0].regex.pattern;
const replacePattern = node.arguments[1].value;
return fixer.replaceText(node, `${stringName}.replaceAll(${quoteString(searchPattern)}, ${quoteString(replacePattern)})`);
}
fisker marked this conversation as resolved.
Show resolved Hide resolved

function checkNode(context, node) {
if (hasGlobalFlag(node) && isLiteralCharactersOnly(node)) {
context.report({
node,
message: 'Use replaceAll method of string.',
fix: fixer => replaceNode(node, fixer)
});
}
}

const create = context => {
return {
'CallExpression[callee.property.name="replace"]': node => {
checkNode(context, node);
}
};
};

module.exports = {
create,
meta: {
type: 'suggestion',
docs: {
url: getDocumentationUrl(__filename)
},
fixable: 'code'
}
};
69 changes: 69 additions & 0 deletions test/prefer-replace-all.js
@@ -0,0 +1,69 @@
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: [
'str.replace(/No global flag/,"123")',
'str.replace(/[abc]/g,"123")',
'str.replace(/abc?/g,"123")',
'str.replace(/Non-literal characters .*/g, "something");',
'str.replace(/Other non-literal \\W/g, "something");',

'str.replace(/Extra flags/gi, "something");',
'str.replace("Not a regex expression", "something")',
'str.methodNotReplace(/Wrong method name/g, "something");'
],
invalid: [
{
code: 'str.replace(/This has no special regex symbols/g, \'something\')',
output: 'str.replaceAll(\'This has no special regex symbols\', \'something\')',
errors: [error]
},
{
code: 'str.replace(/\\(It also checks for escaped regex symbols\\)/g,\'something\')',
output: 'str.replaceAll(\'\\(It also checks for escaped regex symbols\\)\', \'something\')',
errors: [error]
},
{
code: 'str.replace(/a\\\\bc\\?/g,\'123\')',
output: 'str.replaceAll(\'a\\\\bc\\?\', \'123\')',
errors: [error]
},
{
code: 'console.log(str.replace(/a\\\\bc\\?/g,\'123\'))',
output: 'console.log(str.replaceAll(\'a\\\\bc\\?\', \'123\'))',
errors: [error]
},
{
code: 'str.replace(/"doubleQuotes"/g,\'1"2"3\')',
output: 'str.replaceAll(\'"doubleQuotes"\', \'1"2"3\')',
errors: [error]
},
{
code: 'str.replace(/\'singleQuotes\'/g,"1\'2\'3")',
output: 'str.replaceAll(\'\\\'singleQuotes\\\'\', \'1\\\'2\\\'3\')',
errors: [error]
},
{
code: 'str.replace(/searchPattern/g,\'\\\'escapedQuotes\\\'\')',
output: 'str.replaceAll(\'searchPattern\', \'\\\'escapedQuotes\\\'\')',
errors: [error]
}
]
});