Jporter
Jporter

Reputation: 23

Regex returns null for value if there is no match

I'm trying to use Regular Expressions to read a message that a user types, looks for keywords and count them up.

The issue I have is that if there is no match I get this error: Uncaught TypeError: Cannot read property 'length' of null

I don't get that error if there is a match though it will count the amount of times the phrase is entered.

function readMessage() {
    var newtext = $("#myText").val()

    var newMessage = document.createElement("div");
    newMessage.setAttribute("id", "Divjuan");
    var messageText = document.createTextNode(newtext);
    console.log(messageText)
    newMessage.appendChild(messageText);

    var currentDiv = document.getElementById("div1");
    currentDiv.insertBefore(newMessage, currentDiv.childNode);

    var source1 = newtext;
    console.log(source1)
    var exampletcount1 = source1.match(/example1/g).length;
    console.log(exampletcount1)

    var exampletcount2 = source1.match(/example2/g).length;
    console.log(exampletcount2)

}

Any help would be great

Upvotes: 0

Views: 2031

Answers (2)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522712

Check whether or not the match is null before attempting to access its length:

var examplematch1 = source1.match(/example1/g);
var exampletcount1 = examplematch1 ? examplematch1.length : 0;
console.log(exampletcount1);

Upvotes: 1

Ayush Gupta
Ayush Gupta

Reputation: 9305

You can do something like:

let count = (source1.match(/example1/g) || []).length

Here's a sample snippet:

let source1 = "abcd";
console.log((source1.match(/example2/g) || []).length);

Upvotes: 0

Related Questions