Why this in not working

Hi guys why the code blow doesnt work it only replace= “NAME.”, myName
and not the others i even used .replaceAll but i got this error that say .replaceAll is not a function
i know i can use template literals but i want to learn this .replace too

let myAge = 17;
let earlyYears = 2;
earlyYears *= 10.5;
let laterYears = myAge - 2;
laterYears *= 4;
myAgeInDogYears = earlyYears + laterYears;
let myName = "x"
console.log(
  "My name is NAME. I am HUMAN AGE years old in human years which is DOG AGE years old in dog years.".replace(
    "NAME.",
    myName,
    "HUMAN AGE",
    myAge,
    "DOG AGE",
    myAgeInDogYears
  )
);

// output is = My name is x am HUMAN AGE years old in human years which is DOG AGE years old in dog years.

1 Like

The replace method only takes one pattern and one replacement as an argument, same as replaceAll. You aren’t able to add multiple patterns and replacements into one call and stack them. Instead, if you want to use replace then you’ll need to chain multiple, like so:

let myAge = 17;
let earlyYears = 2;
earlyYears *= 10.5;
let laterYears = myAge - 2;
laterYears *= 4;
myAgeInDogYears = earlyYears + laterYears;
let myName = "x"
console.log(
  "My name is NAME. I am HUMAN AGE years old in human years which is DOG AGE years old in dog years.".replace(
    "NAME.",
    myName
  ).replace(
    "HUMAN AGE",
    myAge
  ).replace(
    "DOG AGE",
    myAgeInDogYears
  )
);

Note here we’ve chained multiple replace methods onto each other to ensure everything gets replaced. This also works with replaceAll.

4 Likes

hi
wow thanks for the help , but when i use .replaceAll i get the error that say replaceAll is not a function
but why ?

1 Like

Apologies, replaceAll is still a relatively new string method and as such may not be available yet depending on where you’re trying to use it (e.g. Codecademy’s workspace). If you try in your own workspace via a new version of node it should work, likewise if you tried on an updated browser, however it may not work everywhere yet.

2 Likes

thank you so much for the help

2 Likes