How to fix var.replace is not a function with JavaScript?

Sometimes, we want to fix var.replace is not a function with JavaScript.

In this article, we’ll look at how to fix var.replace is not a function with JavaScript.

How to fix var.replace is not a function with JavaScript?

To fix var.replace is not a function with JavaScript, we should make the variable we’re calling replace on is a string.

For instance, we write

const trim = (str) => {
  return str.toString().replace(/^s+|s+$/g, "");
};

to define the trim function that takes the str parameter.

To make sure that str is a string, we call toString to convert it to a string before we call replace on it.

Conclusion

To fix var.replace is not a function with JavaScript, we should make the variable we’re calling replace on is a string.