Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the second occurrence of a Regexp match in Javascript

I want to get two string from the following url, first is -43.575285, the second is 172.762549

http://maps.apple.com/?lsp=9902&sll=-43.575285,172.762549

I wrote a regexp pattern re = /-?\d+\.\d{6}/;

which only works for the first value, is there any way the matcher can continue search for the result string and give me the second pattern occurrence?

P.S I remember ruby has the $1-$9 to reference the occurrence.

like image 300
mko Avatar asked Jul 31 '13 04:07

mko


2 Answers

Add the g flag to the end...

re = /-?\d+\.\d{6}/g;

This g is for global.

var matches = str.match(re);

Note that this won't work quite like the above if you add capturing groups.

like image 76
alex Avatar answered Nov 01 '22 12:11

alex


var in="http://maps.apple.com/?lsp=9902&sll=-43.575285,172.762549";

var res=in.match(-?\d+\.\d{6}/g);

Now res is an array of matches. If you want second element,

res[1]

would get it for you.

like image 22
schnill Avatar answered Nov 01 '22 10:11

schnill