4

I have the following data posibilities

fnname()
fnname(value)
fnname(value,valueN)

I need a way to parse it with javascript regex to obtain an array

[fnname]
[fnname,value]
[fnname,value,valueN]

Thanks in advance!

6
  • 2
    Do you need to handle nested function calls as in f(g(h(value))) Commented Aug 24, 2014 at 6:51
  • no, just this data set Commented Aug 24, 2014 at 6:53
  • @AvinashRaj: I suspect OP showed [ and ] for array representation. Commented Aug 24, 2014 at 6:59
  • @anubhava yep, now only i realized that. Commented Aug 24, 2014 at 7:01
  • @anubhava yes [] means array representation. sorry if unclear. Commented Aug 24, 2014 at 7:03

5 Answers 5

2

You could try matching rather than splitting,

> var re = /[^,()]+/g;
undefined
> var matches=[];
undefined
> while (match = re.exec(val))
... {
... matches.push(match[0]);
... }
5
> console.log(matches);
[ 'fnname', 'value', 'value2', 'value3', 'value4' ]

OR

> matches = val.match(re);
[ 'fnname',
  'value',
  'value2',
  'value3',
  'value4' ]
Sign up to request clarification or add additional context in comments.

1 Comment

matches = val.match(re) seems simpler than looping.
2

This should work for you:

var matches = string.split(/[(),]/g).filter(Boolean);
  • Regex /[(),]/g is used to split on any of these 3 characters in the character class
  • filter(Boolean) is used to discard all empty results from resulting array

Examples:

'fnname()'.split(/[(),]/g).filter(Boolean);
//=> ["fnname"]

'fnname(value,value2,value3,value4)'.split(/[(),]/g).filter(Boolean);
//=> ["fnname", "value", "value2", "value3", "value4"]

1 Comment

.filter(Boolean) that's something new.
2

Taking some inspiration from other answers, and depending on the rules for identifiers:

str.match(/\w+/g)

Comments

1

Use split like so:

var val = "fnname(value,value2,value3,value4)";
var result = val.split(/[\,\(\)]+/);

This will produce:

["fnname", "value", "value2", "value3", "value4", ""]

Notice you need to handle empty entries :) You can do it using Array.filter:

result = result.filter(function(x) { return x != ""; });

2 Comments

an empty value in the last that should not be there?
What's the point of escaping the comma or parentheses inside the character set? Also, this matches something like "fname(),()((a)", which seems odd.
1

Here's how you can do it in one line:

"fnname(value,value2,value3,value4)".split(/[\(,\)]/g).slice(0, -1);

Which will evaluate to

["fnname", "value", "value2", "value3", "value4"] 

Comments

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.