7

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
0

2 Answers 2

6

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
Sign up to request clarification or add additional context in comments.

2 Comments

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.
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
6

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

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.