Sourav
Sourav

Reputation: 17530

Regexp.match.length returns NULL if not found

I have a JS regexp.

var t1 = str.match(/\[h1\]/g).length;

If str contains the word [h1] it works fine else it shows an error!
How to solve the problem?

Upvotes: 11

Views: 11631

Answers (3)

Ibu
Ibu

Reputation: 43850

how about u do it in 2 steps, you test it first before u get for the length.

var t1 = 0;
var string = str.match(/\[h1\]/g);
if (string){
   t1 = string.length;
}

Upvotes: 2

user166560
user166560

Reputation:

That's the way it's supposed to work. You haven't identified the problem.

If you want to do something based on whether or not str contains "[h1]", try this:

var t1;
var strmatch = str.match((/\[h1\]/g);
if (strmatch !== null) {
    t1 = strmatch.length;
}

Upvotes: 1

kennebec
kennebec

Reputation: 104850

var t1 = (str.match(/\[h1\]/g)||[]).length;

Upvotes: 33

Related Questions