I have been developing a series of validation functions for my static site generation tool. One of these functions involves using various .match()
methods to analyze HTML header tags. Here is the current state of the validation function:
// 2c. Check that each header tag's next header tag is one level higher, lower, or the same level
const headers = html.match(/<h[1-6][^>]*>.*<\/h[1-6]>/g)
headers?.forEach((header, index) => {
if (index === headers.length - 1) return
const currentLevel = parseInt(header.match(/<h([1-6])/)[1])
const nextLevel = parseInt(headers[index + 1].match(/<h([1-6])/)[1])
if (nextLevel && Math.abs(currentLevel - nextLevel) > 1) {
throw new Error(
`Content for ${directory}/${slug}${contentExtension} has an invalid header hierarchy.`
)
}
})
The issue of "Object is possible null
" arises with both header.match(/<h([1-6])/)
and
headers[index + 1].match(/<h([1-6])/)
. Despite encountering this error, the validation function performs as expected in numerous Jest test cases I have created. While I am able to identify why this error occurs and how to trigger the validation function, I am unsure about resolving this null object problem.
In attempts to rectify this situation, I initially used a non-null assertion operator on the problematic parts of the code. However, this approach did not solve the issue. I also experimented with a standard if
null check for the objects. Additionally, I explored checking the index after .match()
, but realized quickly that this was beyond the scope of the error.
Upon exploring suggestions in the "Do any of these posts answer your question" section, I referenced this answer which led to a new error stating "Forbidden non-null assertion".