views:

19

answers:

3

Hello,

re = /\/?(\w+)\/(\w+)/
s = '/projects/new'
s.match(re)

I have this regular expression which I will use to sieve out the branch name, e.g., projects, and the 'tip' name, e.g., new

I read that one can have access to the grouped results with $1, $2, and so on, but I can't seem to get it to work, at least in Firebug console

When I run the above code, then run

 RegExp.$1

it shows

""

Same goes on for $2.

any ideas?

Thanks!

+1  A: 

Without the g flag, str.match(regexp) returns the same as regexp.exec(str). And that is:

The returned array has the matched text as the first item, and then one item for each capturing parenthesis that matched containing the text that was captured. If the match fails, the exec method returns null.

So you can do this:

var match = s.match(re);
match[1]
Gumbo
@Gumbo, @Brian, and @João. Thanks guys for your answers. They look about the same, so I am just voting Gumbo'.
Nik
+1  A: 

match gives you an array of the matched expressions:

> s.match(re)[1]
"projects"
> s.match(re)[2]
"new"
Brian Campbell
+1  A: 

I you are accessing the array of matches the wrong way do something like:

re = /\/?(\w+)\/(\w+)/
s = '/projects/new'
var j = s.match(re)

alert(j[1]);
alert(j[2]);
João Gala Louros