EN
                            
                        TypeScript - TypeError: text.replaceAll is not a function error
                                    
                                    2
                                    answers
                                
                            
                                    3
                                    points
                                
                                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
                                
                                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
                                            0 comments
                                            Add comment
                                        
                                        
                                    
                                    3
                                    points
                                
                                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
                                            0 comments
                                            Add comment
                                        
                                        
                                    