Why Does This Happen?
When you use a regular expression pattern with the String.prototype.replaceAll()
method without specifying the "g
" (global) flag, it throws the following error:
// ES12+
const str = 'foo bar foobaz';
// Error: String.prototype.replaceAll called with a non-global RegExp argument
const newStr = str.replaceAll(/foo/, 'fox');
// ...
The reason this happens is that the global flag is required when using a regular expression with String.prototype.replaceAll()
. Omitting the global flag results in a TypeError
, as illustrated in the example above.
How to Fix the Issue?
To fix this issue, you need to simply include the global (g
) flag with the regular expression. You can do so in the following two ways:
-
Using Literal Notation
If you're using the literal regular expression notation, you can specify the global flag like so:
// ES12+ const str = 'foo bar foobaz'; const newStr = str.replaceAll(/foo/g, 'fox'); console.log(newStr); // 'fox bar foxbaz'
-
Using the RegExp() Constructor
If you're using the
RegExp()
constructor, you can add the global flag in the following way:// ES12+ const str = 'foo bar foobaz'; const newStr = str.replaceAll(new RegExp('foo', 'g'), 'fox'); console.log(newStr); // 'fox bar foxbaz'
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.