Learn Form Validation by Building a Calorie Counter Step 24

Hello~ In this step, the return function doesn’t work when placed after to return “str”. (i.e. It requires a direct return to the .replace line)

Does this imply that str.replace(regex,""); does not update the “str” argument? (because of string’s immutable state, str gets ‘replaced’. Paraphrase: The replaced str is a different str from the param it initially was.)

For example, this returns param.

function x (a, b) {
  return a * b;
}

This is invalid:

function x(a) {
  const regex = /[+]/g;
  a.replace(regex,"");
  return a;

If so, why doesn’t reassigning it to str or a new variable work?

function x(a) {
  const regex = /[+]/g;
  a=a.replace(regex,"");
  return a;
}

function x(a) {
  const regex = /[+]/g;
  let x=a.replace(regex,"");
  x=a;
  return a;
}

a is declared as parameter. the parameter works like a variable, so isn’t needed to assign it again to a variable.

return a.replace(regex, "")

stored the value in x variable. So isn’t needed x = a.

return x;
1 Like

Oops, that was a typo. Looking back, I had the wrong impression from the error code. “Your cleanInputString function should directly return the result of your replace method.” It would work, but not in the context of the exercise. (direct requirement) Thank you~

1 Like