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 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
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');

function checkReplace(node) {
return node.callee.property.name === 'replace';
}

function checkGlobalFlag(node) {
const searchPattern = node.arguments[0];
return Object.prototype.hasOwnProperty.call(searchPattern, 'regex') && searchPattern.regex.flags === 'g';
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why not just searchPattern && searchPattern.regex && searchPattern.regex.flags === 'g'.
I understand flags with i should not pass, but how about other flags like gu?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does the built in replace method have full unicode support? From what I'm reading it seems like it doesn't. And all of the other flags would change the search behavior as well.

}

function checkLiteralCharactersOnly(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.replace(/\\(.)/g, '$1');
Copy link
Collaborator

@fisker fisker Dec 30, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This line is not right, /\\a/g is searching for \a not a, maybe .replace(/\\\\(.)/g, '\\$1')?.

Also, funny thing.

I think we can also replace it with .replace(/\\\\/g, '\\'), then this line will against this rule itself, so maybe .replaceAll('\\\\', '\\')?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm. On second thought, that replace shouldn't be necessary at all. However, I do need to add an escape for any double quotes in the original regex expression.

Yeah, that ocurred to me while I was writing it. Very ironic. I decided not to use replaceAll since it doesn't have support in node yet and it would be transpiled back to the expression I have if we ran it through babel.

const replacePattern = node.arguments[1].value;
return fixer.replaceText(node, stringName + '.replaceAll("' + searchPattern + '", "' + replacePattern + '")');
fisker marked this conversation as resolved.
Show resolved Hide resolved
}

function checkNode(context, node) {
if (checkReplace(node) && checkGlobalFlag(node) && checkLiteralCharactersOnly(node)) {
fisker marked this conversation as resolved.
Show resolved Hide resolved
context.report({
node,
message: 'Use replaceAll method of string.',
fix: fixer => replaceNode(node, fixer)
});
}
}

const create = context => {
return {
CallExpression: node => {
fisker marked this conversation as resolved.
Show resolved Hide resolved
checkNode(context, node);
}
};
};

module.exports = {
create,
meta: {
type: 'suggestion',
docs: {
url: getDocumentationUrl(__filename)
},
fixable: 'code'
}
};
54 changes: 54 additions & 0 deletions test/prefer-replace-all.js
@@ -0,0 +1,54 @@
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.foo(/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]
}
]
});