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 »
24 Comments

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


May 25, 2011 at 4:35 PM // reply »
273 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 »
11,307 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 »
11,307 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 »
11,307 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.


Sep 14, 2012 at 3:38 PM // reply »
1 Comments

Wow that just made my life a whole lot easier. It makes for a great string highlighter:

  • if(typeof String.prototype.highlight !== 'function') {
  • String.prototype.highlight = function(match, spanClass) {
  • var pattern = new RegExp( match, "gi" ),
  • highlight = "<span class='" + spanClass + "'>$&</span>";
  •  
  • return this.replace(pattern, highlight);
  • }
  • }


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
Ben Nadel's Company - Epicenter Consulting Recent Blog Comments
Jun 17, 2013 at 9:45 PM
What If All User Interface (UI) Data Came In Reports?
@Jonah, As I was reading what you wrote, it occurred to me that maybe I do something similar to that in some of my client-side code. In an application I'm working on, there are a bunch of unrelated ... read »
Jun 17, 2013 at 9:36 PM
Object Thinking By David West
@Jonah, Please, don't feel bad at all. I appreciate all that you have contributed to the conversation. And, the more points of view I get, the more confident I am that I will some day, some how und ... read »
Jun 17, 2013 at 9:32 PM
Object Thinking By David West
@Paul, I definitely have a mental hurdle when it comes to discovering better design over time. My brain has this insane urge to just understand how you do something right the first time :) But, eve ... read »
Jun 17, 2013 at 9:29 PM
SOTR 2013 - The Best Conference I Never Went To
I just had to watch this again - amazing :) ... read »
Jun 17, 2013 at 9:28 PM
Working With Inherited Collections In AngularJS
@Ali, You are right - it is confusing. I should have just named it "saveForm()" or "submitForm()" or something to that effect. Then, the saveForm() method could have simply vali ... read »
Jun 17, 2013 at 9:27 PM
Working With Inherited Collections In AngularJS
@Samuel, Good question - that was also bothering me when I wrote the code. Yes, I could have moved it up into AppController. The reason that I didn't for this demo was that I didn't want the AppCon ... read »
Jun 17, 2013 at 9:23 PM
Experimenting With The Amazon Simple Storage Service (S3) API Using ColdFusion
@Josh, My pleasure. It was fun to learn more about this stuff. @Chebby, Will do - we're gonna be moving some stuff over to S3, so I am sure I'll be learning all sorts of interesting things / use ... read »
Jun 17, 2013 at 4:21 PM
Experimenting With The Amazon Simple Storage Service (S3) API Using ColdFusion
Thanks Ben. Would love to see more CF/S3 examples! ... read »
InVision App - Prototyping Made Beautiful With Prototyping Tools