Currently, I am trying to find the number of characters and digits that repeat more than once in a given input string.
For example, if the input is "zzrrcde"
, the output should be 2 as both z
and r
occur more than once.
Here is the function I have written after conducting some research. Instead of using nested loops, I opted for regex. However, I am encountering an error: TS2531 Object is possibly null.
Can someone clarify why this error is happening? The error seems to point to the use of text
in the return statement.
export function duplicateCount(text: string): number {
try{ return text.toLowerCase().split("").sort().join("").match(/(.)\1+/g).length; }
catch(e){ return 0; }
}
console.log(duplicateCount("aabbcde"))
I attempted a different approach by declaring a new variable var newText = text
, but unfortunately, I still face the same error.
export function duplicateCount(text: string): number{
var newText = text;
try{ return newText.toLowerCase().split("").sort().join("").match(/(.)\1+/g).length; }
catch(e){ return 0; }
}
console.log(duplicateCount("aabbcde"))
Could someone please guide me on what could be causing this issue? I am new to TypeScript, so any detailed explanation would be very helpful.