Reputation: 15667
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!
Upvotes: 4
Views: 4090
Reputation:
Taking some inspiration from other answers, and depending on the rules for identifiers:
str.match(/\w+/g)
Upvotes: 2
Reputation: 174816
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' ]
Upvotes: 2
Reputation:
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"]
Upvotes: 1
Reputation: 785761
This should work for you:
var matches = string.split(/[(),]/g).filter(Boolean);
/[(),]/g
is used to split on any of these 3 characters in the character classfilter(Boolean)
is used to discard all empty results from resulting arrayExamples:
'fnname()'.split(/[(),]/g).filter(Boolean);
//=> ["fnname"]
'fnname(value,value2,value3,value4)'.split(/[(),]/g).filter(Boolean);
//=> ["fnname", "value", "value2", "value3", "value4"]
Upvotes: 2
Reputation: 5961
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 != ""; });
Upvotes: 1