Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I want to use replaceAll in typescript and angular 10.

But I get this error: Property 'replaceAll' does not exist on type 'string'.

This is my code:

let date="1399/06/08" console.log(date.replaceAll('/', '_')) 

Output: 13990608

How can fix my typescript to show me this function?

like image 227
behroozbc Avatar asked Aug 27 '20 12:08

behroozbc


People also ask

How do I use replaceAll in TypeScript?

To replace all occurrences of a string in TypeScript, use the replace() method, passing it a regular expression with the g (global search) flag. For example, str. replace(/old/g, 'new') returns a new string where all occurrences of old are replaced with new .

What does in replaceAll () mean in Java?

The replaceAll() method replaces each substring of this string that matches the given regular expression with the given replacement.

What can I use instead of replaceAll in Javascript?

To make the method replace() replace all occurrences of the pattern you have to enable the global flag on the regular expression: Append g after at the end of regular expression literal: /search/g. Or when using a regular expression constructor, add 'g' to the second argument: new RegExp('search', 'g')


2 Answers

You should be able to add those typings through your tsconfig.json. Add "ES2021.String" to lib inside compilerOptions.

Your tsconfig should then look something like this:

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

The replaceAll method is defined inside lib.es2021.string.d.ts as follows:

interface String {     /**      * Replace all instances of a substring in a string, using a regular expression or search string.      * @param searchValue A string to search for.      * @param replaceValue A string containing the text to replace for every successful match of searchValue in this string.      */     replaceAll(searchValue: string | RegExp, replaceValue: string): string;      /**      * Replace all instances of a substring in a string, using a regular expression or search string.      * @param searchValue A string to search for.      * @param replacer A function that returns the replacement text.      */     replaceAll(searchValue: string | RegExp, replacer: (substring: string, ...args: any[]) => string): string; } 
like image 142
Josef Avatar answered Sep 20 '22 23:09

Josef


You may solve the problem using RegExp and global flag. The global flag is what makes replace run on all occurrences.

"1399/06/08".replace(/\//g, "_") // "1399_06_08" 
like image 23
strdr4605 Avatar answered Sep 20 '22 23:09

strdr4605