NOTE: For a FULL TUTORIAL on Javascript String Replace methods, check out this entry: Ask Ben: Javascript String Replace Method.
I was just going through some Javascript code when I came across the coolest thing on BigBold.com. I never knew you could do this, but you can use a nameless method as the "replace" argument to the Javascript String replace() method call. See in the example below that I take a string and turn each non-vowel characer into a randomly upper or lowercase character:
Launch code in new window » Download code as text file »
In this case we are using "$1" to keep the usual formatting of Regular Expressions (RegExp), however, we could have easily named the argument strMatch or something along those lines. The groups found in the RegExp match are passed to the function in the order that they appear (ie. $1, $2, $3, etc.).
The "replace" function argument doesn't need to be confined to the scope of the replace() method call. The "replace" argument is a sub-function just like any other sub function and has access to its parent scope. In the following example, we return an array of the small, common words found in the string. We build this array by declaring prior to the replace() method call and then adding to it for each iteration of the replace() match:
Launch code in new window » Download code as text file »
Download Code Snippet ZIP File
Comments (2) | Post Comment | Ask Ben | Permalink | Other Searches | Print Page
Some of the code in the first example & wording describing it is confusing & possibly misleading:
> function($1){ .... }
>
> The groups found in the RegExp match are passed to the function in the order that they appear (ie. $1, $2, $3, etc.).
The order of parameters passed to any lambda function used in a replace statement is (fullmatchresult, $1, $2 $3, ..)
.. so in your first example, your variable "$1" does not actually equal the $1 result from the regexp match .. it's the full match result.
Posted by carcomplaints.com on Nov 30, 2006 at 11:22 AM
You are exactly correct. This was a misunderstanding on my part. I didn't realize quite what was going on until I started using the Java Pattern Matcher. The Java Pattern matcher has a group() method to which you can pass indexes. The method call with no index returns the full match. Seeing this helped me (in some sort of eureka moment) that I didn't fully understand the way Javascript replace was working.
Thanks for pointing that out for others (as I did not update this blog entry).
Posted by Ben Nadel on Nov 30, 2006 at 12:02 PM