recording positions of multiple substrings that match a regexp

J

Jason S

Is there a way to get the position of multiple substrings that match a
regexp without using closures? match() returns the substrings
themselves, not the positions, and search() seems to only return the
first position. Here's what seems to work (under Shanti Rao's jsdb.exe
shell) but I get a bit nervous about using closures...

function bind_cache(x) { return function (subs,ofs)
{ x.push([ofs,subs.length]); return ""; }}
x=[];
f=bind_cache(x);
s='The quick brown fox jumped over the lazy dogs';
junk=s.replace(/\w*o\w*/g, f);

for (i = 0; i < x.length; ++i) writeln(s.slice(x[0],x[0]+x
[1]));

output (all the words with an 'o'):
brown
fox
over
dogs
 
R

ron.h.hall

Is there a way to get the position of multiple substrings that match a
regexp without using closures? match() returns the substrings
themselves, not the positions, and search() seems to only return the
first position. Here's what seems to work (under Shanti Rao's jsdb.exe
shell) but I get a bit nervous about using closures...

function bind_cache(x) { return function (subs,ofs)
{ x.push([ofs,subs.length]); return ""; }}
x=[];
f=bind_cache(x);
s='The quick brown fox jumped over the lazy dogs';
junk=s.replace(/\w*o\w*/g, f);

for (i = 0; i < x.length; ++i) writeln(s.slice(x[0],x[0]+x
[1]));


var
m,
x = [],
re = /\w*o\w*/ig
;
while ( m = re.exec( s ) ) {
x.push( [m.index, m[0]] );
}
alert( x.join( "\n" ) );

would be more attuned to the underlying facilities.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top