Table of content
We all know the replace() function for JavaScript Strings and that it is possible to do really fancy things by using regular expressions to replace a (sub)string. What I didn’t know was that there are special $ references you can use in the replace() function. Of course there is $1, $2,… to get the first, second finding, BUT did you know $& is also available?
$& reinserts the whole regex match
Here is an example how it works:
The usage of $& is basically just the shorthand of using the replace() function with a function as second parameter:
text.replace(regex, function(m){ return ''+m+'';});When you use replace(RegExp, function) then the function is called with the following arguments:
The matched substring
Match1,2,3,4 etc (parenthesized substring matches)
The offset of the substring
The full string
When to use it?
It will make sense to use $& if you can’t change the regex per se, e.g. if you get it from a server. Or, secondly you just don’t want to employ a captured group in your regular expression ;)
More information:
LingoHub - Translation Management for Developers
This article is provided by LingoHub, a translation management software. It is used by development and product teams from all over the world to manage software translations more productively.
Related articles
Dev Bit: Auto generate UUID with Postgres and Rails 4
Learn how to auto-generate UUIDs with PostgreSQL and Rails 4 using the uuid-ossp extension and database-level defaults.
Dev Bit: How to add plugins to elasticsearch under Mac/Brew
Learn how to install Elasticsearch plugins on Mac with Homebrew, find the right libexec path, and verify plugins like Kopf or Elastic HQ.
Dev Bit: SQL word count & character count with Postgres
Learn how to count words and characters in PostgreSQL with SQL queries for localization projects, translations, and multilingual text analysis.
