Julian Zientkowski
Julian Zientkowski

Reputation: 367

Problem with counting characters in javascript

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

Upvotes: 0

Views: 63

Answers (1)

CherryDT
CherryDT

Reputation: 29052

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

Upvotes: 3

Related Questions