I’m having some trouble translating my working C# regular expression into JavaScript’s regular expression implementation.
Here’s the regular expression:
([a-z]+)((\d+)([a-z]+))?,?
When used on "water2cups,flour4cups,salt2teaspoon" you should get:
[
["water", "2cups", "2", "cups"]
["flout", "4cups", "4", "cups"]
["salt", "2teaspoon", "2", "teaspoon"]
]
… And it does. In C#. But not in JavaScript.
I know there are some minor differences across implementations. What am I missing to get this expression working in JavaScript?
Update
I am using the regex like so:
"water2cups,flour4cups,salt2teaspoon".match(/([a-z]+)((\d+)([a-z]+))?,?/g);
Creating the RegExp
You haven’t shown how you’re creating your Javascript regular expression, e.g., are you using a literal:
or a string
If the latter, note that I’ve escaped the backslash.
Global Flag
By default, Javascript regular expressions are not global, that may be an issue for you. Add the
gflag if you don’t already have it:or
Using
RegExp#execrather thanString#matchYour edit says you’re using
String#matchto get an array of matches. I have to admit I hardly ever useString#match(I useRegExp#exec, as below.) When I useString#matchwith your regex, I get…very odd results that vary from browser to browser. Using aRegExp#execloop doesn’t do that, so that’s what I’d do.Working Example
This code does what you’re looking for:
(The
logfunction just appends text to a div.)My output for that is:
(Recall that in Javascript,
match[0]will be the entire match; thenmatch[1]and so on are your capture groups.)