Special $ References In JavaScript's String.replace() Method

Posted May 25, 2011 at 9:29 AM by Ben Nadel

Tags: Javascript / DHTML

In honor of the 4th Annual Regular Expression Day, I thought I would do some further exploration of Regular Expressions. And, as it so happens, I just learned something new about Javascript regular expressions while reading Javascript: The Good Parts by Douglas Crockford. In the book, Crockford outlines the special characters that are available in the String.replace() method. I had always known about the use of $N to denote captured groups; I was not aware, however, that $&, $`, and $' were also available in the replace() method.

I don't have Javascript: The Good Parts in front of me at the moment. However, I was able to double-check the syntax on Jan Goyvaerts' website (co-author of The Regular Expression Cookbook). On his website, Jan outlines the above replacement references as follows:

  • $& - Refers to the entire text of the current pattern match.
  • $` - Refers to the text to the left of the current pattern match.
  • $' - Refers to the text to the right of the current pattern match.

To see these references in action, I set up the following demo. In this code, our replacement execution is completely non-functional; it is meant only to elucidate the values contained within each replacement reference:

  • <!DOCTYPE html>
  • <html>
  • <head>
  • <title>Using The $ In JavaScript RegEx Replace</title>
  • <script type="text/javascript">
  •  
  •  
  • // Create a test string in which we will match our pattern.
  • var value = "My number is 212-555-1234.";
  •  
  • // Creat the pattern to match the phone number.
  • var pattern = new RegExp( "(\\d+)", "g" );
  •  
  • // Replace into the value the special "$"-based matches.
  • var result = value.replace(
  • pattern,
  • "|-- [$&] [$`] [$'] --|"
  • );
  •  
  • // Output the replacement result to see $ functionality.
  • console.log( result );
  •  
  •  
  • </script>
  • </head>
  • <body>
  • <!-- Left intentionally blank. -->
  • </body>
  • </html>

As you can see in the above code, we are matching each individual group of digits within the phone number contained within the source text. When we execute the String.replace() method, we're simply replacing the captured number with each of the above $-based values.

When we run the above code, we get the following console output:

My number is |-- [212] [My number is ] [-555-1234.] --|-|-- [555] [My number is 212-] [-1234.] --|-|-- [1234] [My number is 212-555-] [.] --|.

This is a little bit hard to read, so I'm going to break out the replacement portion of each match on its own line:

|-- [212] [My number is ] [-555-1234.] --|
|-- [555] [My number is 212-] [-1234.] --|
|-- [1234] [My number is 212-555-] [.] --|.

As you can see, the $& referred to the entire matched pattern (in our case, that was also the first captured group and could be referred to as $1). The &` referred to the entire text value of the source to the left of the current match. And, the $' referred to the entire text value of the source text to the right of the current match.

I can understand the usefulness of $& in order to refer to the match without having to employ a captured group. But, to be honest, I can't quite see how I would ever use the $` and $' references in a Javascript regular expression replace. In any case, it's always fun to learn more about how something works, even if the value of it is not immediately evident.




Reader Comments

May 25, 2011 at 10:11 AM // reply »
22 Comments

Nice one Ben. I can see the usefulness of having the entire match available.


May 25, 2011 at 4:35 PM // reply »
260 Comments

@Ben: They're available in Perl too.

http://www.regular-expressions.info/perl.html

At the beginning of Chapter 7 - Regular Expressions, Crockford says that the JS implementation is very close to the original Bell Labs formulations, with some reinterpretations and extensions from Perl. But I don't know whether these 3 back references came from Bell Labs or Perl.


May 25, 2011 at 4:48 PM // reply »
10,743 Comments

@Andy,

Word up.

@WebManWalking,

Apparently there are also some other $-based references available, but they are browser extensions and are not universally supported by the browsers.


May 25, 2011 at 4:55 PM // reply »
1 Comments

Regular expressions are literals in ECMAscript. Every regex function is available everywhere.


May 25, 2011 at 5:01 PM // reply »
10,743 Comments

@John,

I use the literal notation every now and then, but sometimes I find it hard to swallow. I find that I get a lot of weird slash patterns. It's probably just what I'm used to - I find this:

"\\bfoo\\b"

... easier to read:

/\bfoo\b/

The latter just throws me off with the flippy-floppy slashes.

Just personal preference, though.


Jun 1, 2011 at 10:51 AM // reply »
1 Comments

In a sort of proof-of-concept use of $` and $', you could parse with two regular expressions to get the text between two tags.

You could run the regular expression for the start tag and get $' for everything to the right (or after). With that result you run the regular expression for the end tag and use $` for everything to the left (or before) and you then get the text in between the two tags.

I'm not saying it's the most practical way, but would allow you to find text after some flag you denote as note-worthy. The more practical use of those two, I'm not really sure.


Jun 1, 2011 at 11:02 AM // reply »
10,743 Comments

@John,

I kind of see what you're saying. I'd have to play around with it a bit to wrap my head around it.


Post A Comment

Comment Etiquette: Please do not post spam. Please keep the comments on-topic. Please do not post unrelated questions or large chunks of code. And, above all, please be nice to each other - we're trying to have a good conversation here.

Please review the following issues:

Author Name:


Author Email:

Author Website:

Comment:

Supported HTML tags for formatting: <strong>bold</strong>   <em>italic</em>   <code>code</code>







  • Help Wanted - Find Your Next ColdFusion Job
InVision App - Prototyping Made Beautiful With Prototyping Tools Ben Nadel's Company - Epicenter Consulting Recent Blog Comments
May 21, 2012 at 1:58 AM
Updated: Converting A ColdFusion Query To CSV Using QueryToCSV()
Hi Ben, why do you need to have so many double quotes when adding the field and field name to the row data? ----------------------------------------- <cfset LOCAL.RowData[ LOCAL.ColumnIndex ] = ... read »
AXL
May 21, 2012 at 1:24 AM
URL Rewriting And ColdFusion's WriteToBrowser Image Functionality (CFFileServlet)
@Mounir, Open your lower case URL Rewrite rule and add the following condition. Condition input: {REQUEST_URI} Check if input string: Does Not Match the Pattern Pattern: ^/CFFileServlet/_cf_ca ... read »
May 20, 2012 at 4:28 AM
Understanding The Complex And Circular Relationships Between Objects In JavaScript
@Will Vaughn I tried your javascript example but got this error:- foo.print is not a function ... read »
May 19, 2012 at 5:37 AM
A Graphical Explanation Of Javascript Closures In A jQuery Context
Thanks for this article, but I fear you missed an important point. If variables in the outer context change, these changes affect the inner anonymous functions as well. That means: if you change the ... read »
May 18, 2012 at 3:39 PM
Parsing CSV Data With An Input Stream And A Finite State Machine
Can you use file upload button with this? and read live? or does the file have to already be on the server saved? ... read »
May 18, 2012 at 1:06 AM
VIRGO (Aug. 23-Sept. 22): Dead On The Money!
A friend of mine and I were arguing about astrology and she told me that he believes in astrology. She hasn't provided me with any evidence that the belief makes any sense to me. She she been telling ... read »
May 17, 2012 at 11:32 PM
Using ColdFusion to Handle 404 Errors (Page Not Found) On Development Server
Very easy the configuration. I read a lot pages and I can't find the solution. I open the administrator and change this Administrator/server settings/Error Handlers/Missing Template Handler and p ... read »
May 17, 2012 at 3:13 PM
LOCAL Variables Scope Conflicts With ColdFusion Query of Queries
I never cease to be amazed that almost EVERY random CF issue I come across lands me on your site. Thank you for documenting your findings for the world. ... read »