replace()

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, '');

"elloavacriptorld"

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

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

"elloJavaScriptWorld"

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, "_$&");

"_Hello_Java_Script_World"

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");

"_Hello_Java_Script_World"

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 = "stoyan@phpied.com";
var username = email.replace(/(.*)@.*/, "$1");

username;
"stoyan"
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.

snippet
function replaceCallback(match) {
    return "_" +
        match.toLowerCase();
}

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

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 ' +
        arguments[3];
}

We can then call this as follows:

"stoyan@phpied.com".replace(re, callback);

"stoyan at phpied dot com"

Here's what the callback function received as arguments:

glob

["stoyan@phpied.com", "stoyan", "phpied", "com", 0, "stoyan@phpied.com"]
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +