0

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;
4
  • match can return null if no result is found. Commented May 3, 2016 at 7:08
  • But vrb1 returns a value Commented May 3, 2016 at 7:10
  • match returns an array (or null if no match), not a string. Use var vrb1 = str.match(regex) || [] so then you'll know vrb1 is a (possibly empty) array. Commented May 3, 2016 at 7:19
  • Also note that when using the RegExp constructor, back slashes must also be quoted, so new RegExp("[\\(]([^\\)])+[\\)]","g") or use a literal: /[\(]([^\)])+[\)]/g; Commented May 3, 2016 at 7:26

2 Answers 2

3

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(',');
}
Sign up to request clarification or add additional context in comments.

Comments

2

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(",") : [];

2 Comments

Half way there. match returns null or an array. Arrays don't have a split method.
@RobG thanks, i had missed out that OP is further splitting the results by comma.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.