So currently, my code works for inputs that contain one set of parentheses.
var re = /^.*\((.*\)).*$/;
var inPar = userIn.replace(re, '$1');
...meaning when the user enters the chemical formula Cu(NO3)2, alerting inPar returns NO3) , which I want.
However, if Cu(NO3)2(CO2)3 is the input, only CO2) is being returned.
I'm not too knowledgable in RegEx, so why is this happening, and is there a way I could put NO3) and CO2) into an array after they are found?
Your regex has anchors to match beginning and end of the string, so it won't suffice to match multiple occurrences. Updated code using
String.match
with the RegExpg
flag (global modifier):In case you need old IE support:
Array.prototype.map
polyfillOr without polyfills:
Above matches a
(
and captures a sequence of zero or more non-)
characters, followed by a)
and pushes it to theinPar
array.The first regex does essentially the same, but uses the entire match including the opening
(
parenthesis (which is later removed by mapping the array) instead of a capturing group.From the question I assume the closing
)
parenthesis is expected to be in the resulting strings, otherwise here are the updated solutions without the closing parenthesis:For the first solution (using
s.slice(1, -1)
):For the second solution (
\)
outside of capturing group):You could try the below:
You want to use String.match instead of String.replace. You'll also want your regex to match multiple strings in parentheses, so you can't have ^ (start of string) and $ (end of string). And we can't be greedy when matching inside the parentheses, so we'll use .*?
Stepping through the changes, we get: