JavaScript replaceAll(): Replace All Occurrences in a String
This Snippet is coded by a user inOnline javascript Compiler. You can see and run this code too.
زبان: JavaScript
String.prototype.replaceAll() creates a new string by replacing every occurrence of a search pattern. It accepts a literal string or a global regular expression as the search value, plus a replacement string or callback function. If the search value is a regular expression without the g flag, JavaScript throws a TypeError. The original string remains unchanged because JavaScript strings are immutable. The method is available in modern browsers and Node.js 15+.
Inputs and outputs: the method takes the search value and replacement. For example, 'a-b-c'.replaceAll('-', '_') returns 'a_b_c'. A callback receives the matched text, its offset, and the original string; with a regex it also receives capture groups. Use /cat/gi for case-insensitive global replacement. Special replacement patterns such as $& insert the matched substring.
Time complexity: average case is O(n), where n is the input length, thanks to optimized searching in modern engines. Worst-case is O(n*m), where m is the pattern length, if the engine performs naive matching. Space complexity is O(n) for the returned string.
Use replaceAll() when every match must change; use replace() when only the first match should change. Test edge cases such as empty search strings and non-global regexes.