Slartibartfast
Slartibartfast

Reputation: 8805

Javascript search and replace

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.

Upvotes: 7

Views: 3254

Answers (2)

Aaron Maenpaa
Aaron Maenpaa

Reputation: 122910

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";
});

Upvotes: 6

Konrad Rudolph
Konrad Rudolph

Reputation: 545608

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/

Upvotes: 6

Related Questions