How to count the number of replacements w/ replace?

S

Sally B.

Hi,
Using string.replace with regular expressions, is there any way to
count the number of replacements that actually happens? I know you can
limit the number of replacements w/ a count value, but how can one
count the actual number of times that an expression gets replaced?

Thanks,
Sally
 
E

Evertjan.

Sally B. wrote on 26 mrt 2005 in comp.lang.javascript:
Using string.replace with regular expressions, is there any way to
count the number of replacements that actually happens? I know you can
limit the number of replacements w/ a count value, but how can one
count the actual number of times that an expression gets replaced?

Don't use global: /g
use a: while () {}
with a counter: count++

or use a global .match count of the to be replaced.
I know you can limit the number of replacements w/ a count value

Please show me/us how.
 
M

Mick White

Sally said:
Hi,
Using string.replace with regular expressions, is there any way to
count the number of replacements that actually happens? I know you can
limit the number of replacements w/ a count value, but how can one
count the actual number of times that an expression gets replaced?

String.match(regexp) will yield an array of matches, the first entry of
which is the String.
Thus the number of matches is Array.length-1.
Mick
 

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
474,436
Messages
2,571,696
Members
48,796
Latest member
Greg L.
Top