const letsMatch = (string, char) => {
const newRegex = new RegExp(char, "gi");
let result = string.match(newRegex);
const findNegIndex = result.indexOf(char);
if (findNegIndex === null) {
return result = 0;
} else {
if (result.length === 2) {
const findFirstIndex = fiveT.indexOf(char);
const findSecondIndex = fiveT.indexOf(char, findFirstIndex + 1);
result = findSecondIndex - findFirstIndex + 2;
return result;
} else {
return (result = 0);
}
}
}
console.log(letsMatch('totititiTo', 'r'))
line 4: const findNegIndex = result.indexOf(char); Throws Uncaught TypeError: Cannot read properties of null (reading ‘indexOf’).
>Solution :
According to the documentation, String.prototype.match() will return null (not an empty array) when no matches are found.
And no matches are found.
You can default to an empty array when it returns null:
const letsMatch = (string, char) => {
const newRegex = new RegExp(char, "gi");
let result = string.match(newRegex) || []; // here
const findNegIndex = result.indexOf(char);
if (findNegIndex === null) {
return result = 0;
} else {
if (result.length === 2) {
const findFirstIndex = fiveT.indexOf(char);
const findSecondIndex = fiveT.indexOf(char, findFirstIndex + 1);
result = findSecondIndex - findFirstIndex + 2;
return result;
} else {
return (result = 0);
}
}
}
console.log(letsMatch('totititiTo', 'r'))
(As an aside, it’s not really clear what this function is meant to accomplish, or what you expect return result = 0 to mean other than return 0. But at the very least the error is because you’re assuming string.match will always return an array, and there exists a use case where it does not.)