views:

551

answers:

2

I would like do do the following in Javascript (pseudo code):

myString.replace(/mypattern/g, f(currentMatch));

that is, replace string isn't fixed, but function of current match.

+6  A: 

Just omit the argument, i.e. use this:

myString.replace(/mypattern/g, f);

Here's an example: http://ejohn.org/blog/search-and-dont-replace/

Konrad Rudolph
+2  A: 

MDC claims that you can do just that:

function styleHyphenFormat(propertyName)
{
  function upperToHyphenLower(match)
  {
    return '-' + match.toLowerCase();
  }
  return propertyName.replace(/[A-Z]/, upperToHyphenLower);
}

Or more generically:

myString.replace(/mypattern/g, function(match){
    return "Some function of match";
});
Aaron Maenpaa
MDC was my first pick, but it was down when I tried to see it. Other sites I've found had only simple examples of replace.
Slartibartfast
This was introduced in JavaScript 1.3. The old JS docs from Netscape 4 can be useful to check JavaScript constructs because almost all of it constitutes old-school JS with "DOM Level 0" that will be supported everywhere. see eg. Sun's mirror at http://docs.sun.com/source/816-6408-10/contents.htm
bobince