Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 673
Slartibartfast Avatar asked Feb 04 '09 17:02

Slartibartfast


2 Answers

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";
});
like image 190
Aaron Maenpaa Avatar answered Sep 28 '22 02:09

Aaron Maenpaa


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/

like image 29
Konrad Rudolph Avatar answered Sep 28 '22 02:09

Konrad Rudolph