Reputation: 57
I extracted a string inside a parenthesis using a simple RegExp expression. I'm trying to split the result to an array.
But I am getting a "Cannot read property 'split' of null" ERROR
. Which is weird because vrb1
returns (a, b)
.
I already tried converting vrb1
to string with toString()
but It didn't work.
Could this error be because of RegExp match result? Your help is very much appreciated.
str = sample(a, b);
var regex = new RegExp("[\(]([^\)])+[\)]","g");
var vrb1 = str.match(regex);
var tmp = vrb1.split(",");
return tmp;
Upvotes: 0
Views: 641
Reputation: 68443
match
will return null if no result is found.
You need simply check for null as well.
Replace
var tmp = vrb1.split(",");
with
var tmp = vrb1 || [];
This will return an empty array if no result is found.
Edit
Looks like you are further splitting the result by comma
, then try
var tmp = vrb1 ? vrb1[0].split(",") : [];
or since there are multiple results (g
in your regex)
var tmp = vrb1 ? vrb1.join(",").split(",") : [];
Upvotes: 2
Reputation: 39466
match
returns an array, not a string.
Return value
array
An Array containing the entire match result and any parentheses-captured matched results, or null if there were no matches.
In your case you want something like:
if (vrb1 !== null) {
var tmp = vrb1[0].split(',');
}
Upvotes: 3