Languages

TypeScript - TypeError: text.replaceAll is not a function error

3 points
Asked by:
a_horse
538

When I try to use the replaceAll method, the compiler yields the error below. How can make it work?

Error message:

TypeError: text.replaceAll is not a function

My code:

let text: string = 'a xxx b xxx c';

const letter: string = 'x';
const replacement: string = 'y';

text = text.replaceAll(letter, replacement);
2 answers
7 points
Answered by:
a_horse
538

I don't know in what environment you want to use String replaceAll() method, but that function appeard in ES2021. So, add ES2021.String lib in tsconfig.json.

Example tsconfig.json file:

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

Running compiled/transpiled TypeScript source code into JavaScript, be sure that you use modern web browser, Polyfill or Node.js >= v16.

See also

  1. JavaScript - ECMAScript / ES versions and features

0 comments Add comment
3 points
Answered by:
a_horse
538

You can simply use replace() method with a regular expression with the global flag instead.

Practical example:

let text: string = 'a xxx b xxx c';

text = text.replace(/x/g, 'y');

console.log(text);

// Output:
// a yyy b yyy c

 

See also

  1. TypeScript - replace all occurrences of string 
0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join