replace() allows you to replace the matched text with some other string. The following example removes all capital letters (it replaces them with blank strings):

s.replace(/[A-Z]/g, '');


If you omit the g modifier, you're only going to replace the first match:

s.replace(/[A-Z]/, '');


When a match is found, if you want to include the matched text in the replacement string, you can access it using $&. Here's how to add an underscore before the match while keeping the match:

s.replace(/[A-Z]/g, "_$&");


When the regular expression contains groups (denoted by parentheses), the matches of each group are available as $1 is the first group, $2 the second and so on.

s.replace(/([A-Z])/g, "_$1");


Imagine you have a registration form on your web page that asks for email address, username, and password. The user enters their email, and then your JavaScript kicks in and suggests the username, taking it from the email address:

var email = "";
var username = email.replace(/(.*)@.*/, "$1");

Replace callbacks

When specifying the replacement, you can also pass a function that returns a string. This gives you the ability to implement any special logic you may need before specifying the replacements.

function replaceCallback(match) {
    return "_" +

s.replace(/[A-Z]/g, replaceCallback);

The callback function will receive a number of parameters (we ignored all but the first one in the example above):

  • The first parameter is the match
  • The last is the string being searched
  • The one before last is the position of the match
  • The rest of the parameters contain any strings matched by any groups in your regex pattern

Let's test this. First, let's create a variable to store the whole arguments array passed to the callback function:

var glob;

Next, we'll define a regular expression that has three groups and matches email addresses in the format something@something.something:

var re = /(.*)@(.*)\.(.*)/;
Finally, we'll define a callback function that stores the arguments in glob and then returns the replacement:
var callback = function() {
    glob = arguments;
    return arguments[1] + ' at ' + arguments[2] + ' dot ' +

We can then call this as follows:

"".replace(re, callback);

"stoyan at phpied dot com"

Here's what the callback function received as arguments:


["", "stoyan", "phpied", "com", 0, ""]
Related Tutorial
Follow Us #
Contents +