Trigger Error: Null value in search string

Quick question

This is my string:

if (DNS.qname.search('fake-news') > -1) {
log(DNS.qname);
}

I’m getting the following error:

Uncaught TypeError: Cannot ready property 'search' of null

Anyone have any idea why this is happening?

Hi @dlevenden!

What’s happening is that during the event that this trigger is firing, the property “qname” is not defined. In other words, it’s empty, and the javascript engine can’t perform a search on nothing. You’ll want to check that it exists first, before performing a search.

i.e.

if (DNS.qname) {
    if (DNS.qname.search('fake-news') > -1) {
        log(DNS.qname)
    }
}

If DNS.qname exists, the first IF statement will return true, and execute the next line of code. If it doesn’t exist, the IF statement will return false, and not execute the block of code.

Roger. I’ll try that and let you know. Thanks.

To avoid too many nested braces, it’s common to shorten this pattern into one clause, using the && operator:

if (DNS.qname && DNS.qname.search('fake-news') > -1) {
    log(DNS.qname);
}

It does the same thing as the code @apax provided above.

2 Likes