Property 'replaceAll' does not exist on type 'string'

avatar

Borislav Hadzhiev

Last updated: Mar 5, 2022

banner

Photo from Unsplash

Property 'replaceAll' does not exist on type 'String' #

To solve the "Property 'replaceAll' does not exist on type 'string'" error, add the string "ES2021.String" to the lib array in your tsconfig.json file and make sure you are running a recent version of TypeScript.

Open your tsconfig.json file and add ES2021.String to your lib array.

tsconfig.json
{ "compilerOptions": { // ... other options "lib": [ // ... other libs "ES2021.String" ] } }

This will resolve the error and you will be able to use the replaceAll() method.

index.ts
const str = 'old old world'; const result = str.replaceAll('old', 'new'); console.log(result); // 👉️ "new new world"

If you are still unable to use the replaceAll method, make sure you're running a recent version of TypeScript.

shell
npm install -g typescript@latest npm install --save-dev typescript@latest
If you are using Angular.js, you might have to update your version if the error persists.

An alternative solution is to use the replace method with the g flag instead of replaceAll.

index.ts
const str = 'old old world'; const result = str.replace(/old/g, 'new'); console.log(result); // 👉️ "new new world"

We pass the following 2 parameters to the String.replace method:

  1. A regular expression to match. Notice that we use the g (global) flag to specify that we want to match all occurrences and not just the first one
  2. A replacement string

If you have to replace all occurrences of a case insensitive string, you can pass a regular expression to the replaceAll or replace methods.

index.ts
const str = 'old OLD world'; const result = str.replace(/old/gi, 'new'); console.log(result); // 👉️ "new new world"

The i flag enables case-insensitive search. For a complete list of regex flags, check out this table in the MDN docs.

The replace and replaceAll methods do not change the original string, instead they return a new string with the matches replaced. Strings are immutable in JavaScript (and TypeScript).

The replace method is older and more widely supported than replaceAll.

Conclusion #

To solve the "Property 'replaceAll' does not exist on type 'string'" error, add the string "ES2021.String" to the lib array in your tsconfig.json file and make sure you are running a recent version of TypeScript.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.