skip to Main Content

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


  1. If you are using Typescript, please do the following in your tsconfig.json

    {
        ...,
        "compilerOptions": {
            ...,
            "lib": [
              ...,
              "ES2021.String"
            ]
        }
    }

    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.

    Login or Signup to reply.
  2. If you use javascript, you can change the code as follows

    var variable2 = "blah,blah,blah12345";
    var variable1 = variable2.replaceAll(/D/g,'');
    console.log(variable1);
    

    Then you can get the results 12345.

    Login or Signup to reply.
  3. You can just remove the All from replaceAll as the g in /D/galready represents the same functionality – see following snippet which returns 12345

    variable2="blah,blah,blah12345";
    variable1=variable2.replace(/D/g,'');
    console.log(variable1);
    Login or Signup to reply.
  4. The following code will work parfectly

    variable2 = "blah,blah,blah12345"; variable1 = variable2.replaceAll(/D/g, '');
    

    console.log(variable1);

    Login or Signup to reply.
  5. function replaceAll is only available in Node version 15 and above.

    Check the version compatibikity of replaceAll here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search