I was trying to run the replace command, but an error occurred:"Uncaught TypeError: variable2.replaceAll is not a function"
Here’s what I tried:
variable2="blah,blah,blah12345";
variable1=variable2.replaceAll(/D/g,'');
console.log(variable1);
I thought varible2 would equal "12345" but instead I got the error: "Uncaught TypeError: varible2.replaceAll is not a function".
6
Answers
If you are using Typescript, please do the following in your tsconfig.json
I tried running your code in Typescript playground and it is showing the same error when running in ES2020 version or lower. The replaceAll method in String is supported from ES2021.
If you use javascript, you can change the code as follows
Then you can get the results
12345
.You can just remove the
All
fromreplaceAll
as theg
in/D/g
already represents the same functionality – see following snippet which returns12345
You’re probably using some kind of strict script parser, and using
var2
wrongly somewhere. Below it is being outputted in a non-strict mode. Notice that the variable value, the function itself, and the return of that function are all being outputted correctly. Make sure if you want the output of a function performed on it, to use choice 3. If you want just the raw value, use choice 1.The following code will work parfectly
console.log(variable1);
function replaceAll is only available in Node version 15 and above.
Check the version compatibikity of replaceAll here