Skip to content

Commit

Permalink
prefer-replace-all: Handle u flag (#879)
Browse files Browse the repository at this point in the history
  • Loading branch information
fisker committed Oct 20, 2020
1 parent d10a641 commit d98d867
Show file tree
Hide file tree
Showing 5 changed files with 68 additions and 1 deletion.
16 changes: 16 additions & 0 deletions docs/rules/prefer-replace-all.md
Expand Up @@ -8,14 +8,30 @@ This rule is fixable.

```js
string.replace(/This has no special regex symbols/g, '');
```

```js
string.replace(/\(It also checks for escaped regex symbols\)/g, '');
```

```js
string.replace(/Works for u flag too/gu, '');
```

## Pass

```js
string.replace(/Non-literal characters .*/g, '');
```

```js
string.replace(/Extra flags/gi, '');
```

```js
string.replace('Not a regex expression', '')
```

```js
string.replaceAll('Literal characters only', '');
```
7 changes: 6 additions & 1 deletion rules/prefer-replace-all.js
Expand Up @@ -15,7 +15,12 @@ const selector = methodSelector({

function isRegexWithGlobalFlag(node) {
const {type, regex} = node;
return type === 'Literal' && regex && regex.flags === 'g';
if (type !== 'Literal' || !regex) {
return false;
}

const {flags} = regex;
return flags.replace('u', '') === 'g';
}

function isLiteralCharactersOnly(node) {
Expand Down
9 changes: 9 additions & 0 deletions test/prefer-replace-all.js
Expand Up @@ -13,8 +13,12 @@ test({
'foo.replace(/a?/g, bar)',
'foo.replace(/.*/g, bar)',
'foo.replace(/\\W/g, bar)',
'foo.replace(/\\u{61}/g, bar)',
'foo.replace(/\\u{61}/gu, bar)',
// Extra flag
'foo.replace(/a/gi, bar)',
'foo.replace(/a/gui, bar)',
'foo.replace(/a/uig, bar)',
// Not regex literal
'foo.replace(\'string\', bar)',
// Not 2 arguments
Expand Down Expand Up @@ -82,3 +86,8 @@ test({
}
]
});

test.visualize([
'foo.replace(/a/gu, bar)',
'foo.replace(/a/ug, bar)'
]);
37 changes: 37 additions & 0 deletions test/snapshots/prefer-replace-all.js.md
@@ -0,0 +1,37 @@
# Snapshot report for `test/prefer-replace-all.js`

The actual snapshot is saved in `prefer-replace-all.js.snap`.

Generated by [AVA](https://avajs.dev).

## prefer-replace-all - #1

> Snapshot 1
`␊
Input:␊
1 | foo.replace(/a/gu, bar)␊
Output:␊
1 | foo.replaceAll('a', bar)␊
Error 1/1:␊
> 1 | foo.replace(/a/gu, bar)␊
| ^^^^^^^^^^^^^^^^^^^^^^^ Prefer `String#replaceAll()` over `String#replace()`.␊
`

## prefer-replace-all - #2

> Snapshot 1
`␊
Input:␊
1 | foo.replace(/a/ug, bar)␊
Output:␊
1 | foo.replaceAll('a', bar)␊
Error 1/1:␊
> 1 | foo.replace(/a/ug, bar)␊
| ^^^^^^^^^^^^^^^^^^^^^^^ Prefer `String#replaceAll()` over `String#replace()`.␊
`
Binary file added test/snapshots/prefer-replace-all.js.snap
Binary file not shown.

0 comments on commit d98d867

Please sign in to comment.