I want to count all of 'O' appearances in a given string, but when there are none, an error pops up.
const string = 'PIWWS'
function count(str, letter) {
const re = new RegExp(letter, 'g');
const count = str.match(re).length;
return count;
}
if (count (string, 'O') == 1) {
console.log('success')
} else {
console.log('fail')
}
this code outputs:
const count = str.match(re).length;
^
TypeError: Cannot read properties of null (reading 'length')
at count (C:\Users\Julian\Desktop\index.js:5:32)
at Object.<anonymous> (C:\Users\Julian\Desktop\index.js:9:5)
←[90m at Module._compile (node:internal/modules/cjs/loader:1105:14)←[39m
←[90m at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)←[39m
←[90m at Module.load (node:internal/modules/cjs/loader:981:32)←[39m
←[90m at Function.Module._load (node:internal/modules/cjs/loader:822:12)←[39m
←[90m at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)←[39m
←[90m at node:internal/main/run_main_module:17:47←[39m
When i add an 'O' to the string variable the output is 'success' as expected
if (string.includes('O')) ...'fail'ifstringcontains more than one occurrence ofletter; is that what you want? Furthermore, if you just want to check whether a letter or substring is present in a string, no matter how many times, you might want to consider usingString.prototype.includes()orRegExp.prototype.test(), which both return a boolean