Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

119
Views
problem with ".match(/\w+/g).length" in react

Using .match(/\w+/g).length while counting the number of words, returns an error if space is given at beginning of a sentence. How do i make it error-free?

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

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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.
about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!