0

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

3
  • this could be written much simpler as if (string.includes('O')) ... Commented Oct 10, 2022 at 15:48
  • Just a side note: as it is now, your code will log 'fail' if string contains more than one occurrence of letter; 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 using String.prototype.includes() or RegExp.prototype.test(), which both return a boolean Commented Oct 10, 2022 at 15:50
  • str.match(re)?.length or (str.match(re) || "").length to avoid the not matching issues Commented Oct 10, 2022 at 16:12

1 Answer 1

3

Should be str.match(re)?.length ?? 0, remember that match returns null and not an empty array if no matches are found.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.