Home > Enterprise >  problem with ".match(/\w /g).length" in react
problem with ".match(/\w /g).length" in react

Time:06-02

Using ".match(/\w /g).length" while counting number of words, returns error if space is given at beginning of sentence. how do i make it error free?

The error says "can't read the properties of null (reading 'length')"

CodePudding user response:

Try this str.match(/(\w )/g).length

CodePudding user response:

match returns null when no matches were found. In your case, it is when there are no words (empty strings or just white spaces). In other cases, it is an array. You should check if the result of the match is null before checking the .length.

One way to overcome this error, suppose str is the string you are checking:

const matchStr = str.match(/\w /g) || []; // The || [] will give you empty array instead of null when no matches were found
matchStr.length // now you can safely use .length property, because you will always have an array.
  • Related