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?
414 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; } 14You 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" 3From the docs:
As of August 2020 the
replaceAll()method is supported by Firefox but not by Chrome. It will become available in Chrome 85.
Meanwhile you could find multiple other methods here.
Screenshot for possible future readers:
3That is because TypeScript does not recognize newer methods, than his current JavaScript version. String.replaceAll() is defined is ES2021.
You have to add the lib in compilerOptions, on the tsconfig.json file.
The value of lib must be either: ["ES2021"], or specifically the string typing ["ES2021.String"].
Add the following on the tsconfig.json file:
{ ... "compilerOptions": { "lib": ["ES2021"] ... } 1Just Use this function
let date="1399/06/08" console.log(date.split('/').join('_'))2You can create a file
myOwnTypes.d.ts
at the root of your angular project and add the following code:
interface String { replaceAll(input: string, output : string): any; }That will tell typescript that strings has this property.
Now replaceAll is supported in Chrome and Firefox but is always good to check the caniuse to check if it fits your needs.
If this works for you upvotes are more than welcome, Im starting with this stackoverflow account and would appreciate the support :)
Another possible solution: I had this issue but my tsconfig target was set to "es2021". The cause, there was also one lib being specified. So by using the lib and the target, it overrided the defaults to the lib. The solution completely remove the lib or add it to the lib options.
Example: "compilerOptions":{ ..."target": "ES2021" }
or
"complierOptions":{
"target": "ES2021", "lib": [ ..., "ES2021.String" ],
If anyone is still having this issue, add this to your tsconfig.json
{ ..., "compilerOptions": { ..., "lib": [ ..., "esnext.string" ] } } Chrome supports replaceAll so it is safe to use. However typescript still issues an error, so you may cast your string to any, in order to overcome that obstacle.
const date: any ="1399/06/08" console.log(date.replaceAll('/','_')) 2A simple alternative to replace all using RegExp.
let subject = '1399/06/08'; let substring = '/'; let replacement = '_'; let newSubject = subject.replace(new RegExp(substring, 'g'), replacement); console.log(newSubject); Notice that you can make it as a function that takes substring and replacement as string inputs, which is practical.
My use-case was creating an Angular "Replace" Pipe.
This can also happen with a correct tsconfig if the file is not used/imported anywhere and not part of tsconfig.files
According to MDN Web Docs,
"to perform a global search and replace, include the
gswitch in the regular expression".
So, you can try doing:
const date="1399/06/08" const forwardSlashRegex = /(\/)/g; console.log(date.replace(forwardSlashRegex, '_'));This automatically replaces all forward slashes with the underscore. Make sure to also keep the /g global indicator at the end of the regex, as it allows JS to know that you want to replace ALL places where the forward slash occurs.
For more info on the use of regex indicators, refer to the following very useful guide:
In latest versions, you need to set the target attribute in compilerOptions.
{ "compilerOptions": { "module": "commonjs", "declaration": true, "removeComments": true, "emitDecoratorMetadata": true, "experimentalDecorators": true, "allowSyntheticDefaultImports": true, "target": "ES2021", // add this line to use ES2021 "sourceMap": true, "outDir": "./dist", "baseUrl": "./", "incremental": true, "skipLibCheck": true, "strictNullChecks": false, "noImplicitAny": false, "strictBindCallApply": false, "forceConsistentCasingInFileNames": false, "noFallthroughCasesInSwitch": false, "noUnusedLocals": false, "paths": { "@/*": ["src/*"], "@auth/*": ["src/auth/*"], "@aws/*": ["src/aws/*"], "@common/*": ["src/common/*"], "@conig/*": ["src/conig/*"], "@schemas/*": ["src/schemas/*"], } }} I had the same issue. It seems like the issue is due to primitive string. I converted my string variable to String object and then the replaceAll() method did not cause runtime error.
