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.
asked Feb 4, 2009 at 17:26
Slartibartfast
8,8156 gold badges45 silver badges45 bronze badges
2 Answers 2
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";
});
answered Feb 4, 2009 at 17:33
Aaron Maenpaa
124k11 gold badges99 silver badges108 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Slartibartfast
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.
bobince
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 docs.sun.com/source/816-6408-10/contents.htm
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/
answered Feb 4, 2009 at 17:30
Konrad Rudolph
550k142 gold badges968 silver badges1.3k bronze badges
Comments
lang-js