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

String.prototype.replaceAll #1310

Closed
azu opened this issue May 5, 2021 · 3 comments · Fixed by #1314
Closed

String.prototype.replaceAll #1310

azu opened this issue May 5, 2021 · 3 comments · Fixed by #1314

Comments

@azu
Copy link
Collaborator

azu commented May 5, 2021

String.prototype.replaceAll

#1182 はES2020で、ES2021でreplaceAll

replaceメソッドには正規表現も指定できます。 gフラグを有効化した正規表現を渡すことで、文字列からパターンにマッチするものをすべて置換できます。
https://jsprimer.net/basic/string/#replace-delete

があるので、これの別解としてreplaceAllは追加するのが妥当。
用途的には正規表現を使わずにすべてを置換したい場合となる。
正規表現も渡せるが /g がないとエラーとなることについて触れる。

Regular expressions (RegExp) • JavaScript for impatient programmers (ES2021 edition)

Originally posted by @azu in #1220 (comment)

@azu azu mentioned this issue May 5, 2021
6 tasks
@azu
Copy link
Collaborator Author

azu commented May 9, 2021

replaceAllのポイント

  • split joinなしで文字列を使った全置換ができる
  • //g なしの正規表現は渡せない

tc39/proposal-string-replaceall: ECMAScript proposal: String.prototype.replaceAll でもモチベーションは書かれているけど、正規表現を使わずに全置換したいという感じ。
正規表現だとエスケープが必要となるため面倒となっている。

かつではFirefoxだけ replaceの第三引数で "g" が存在した

https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/String/replace#firefox-specific_notes

@azu
Copy link
Collaborator Author

azu commented May 9, 2021

事前に正規表現のエスケープも紹介してるので、素直にreplaceAllを追加するだけで問題なさそう。
https://jsprimer.net/basic/string/#regexp-object

@azu
Copy link
Collaborator Author

azu commented May 9, 2021

ユースケースではString#replaceをHTML文字列をエスケープするで使っている。
String#replaceAllに変更もできるけど、そこまで積極的に変更する理由はなさそう。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant