BrainLikeADullPencil
BrainLikeADullPencil

Reputation: 11653

JavaScript replace

In the following code, the alert(a) inside the JavaScript replace function will alert the matched strings, which, in this case, will be {name} and {place}.

This works as described by the documentation javascript docs , namely, the first argument to the function in the replace method will be the matched string. In the code below, the alert(b) will alert 'name' and 'place' but without the curly braces around them.

Why is that? How does it strip the curly braces for 'b'? Here's a fiddle http://jsfiddle.net/mjmitche/KeHdU/

Furthermore, looking at this example from the docs,

function replacer(match, p1, p2, p3, offset, string){
  // p1 is nondigits, p2 digits, and p3 non-alphanumerics
  return [p1, p2, p3].join(' - ');
};

Which of the parameters in this example would the 'b' in function(a,b) of the replace function below represent?

Part of my failure to understand might be due to the fact that I'm not sure what javascript does, for example, with the second parameter if the maximum number of arguments aren't used.

code

var subObject = {
    name:  "world",
    place: "google"

}; 

var text = 'Hello, {name} welcome to {place}';


var replace = function (s, o) {
            return s.replace(/\{([^{}]*)\}/g,
              function (a, b) {
                  alert(a);
                  alert(b);
                var r = o[b];

                return typeof r === 'string' || typeof r === 'number' ? r : a;
              }
            );
}; 

var replacedText = replace(text, subObject); 
alert(replacedText); ​

Upvotes: 2

Views: 632

Answers (3)

jermel
jermel

Reputation: 2336

See https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/replace on how to use a replacement function

function replacer(match, p1, p2, p3, offset, string){
    // p1 is nondigits, p2 digits, and p3 non-alphanumerics
    return [p1, p2, p3].join(' - ');
};

match: is the entire matched substring (ie what matched the regex)

p1, p2 .... pn: are The nth parenthesized submatch string (within your matched substring)

offset: offset in the original string

string: input string

in your case you didnt supply the full arguments

s.replace(a, b /*, offset, string*/)

so a=match and b=p1

** Note that the function will be invoked multiple times for each full match to be replaced if the regular expression in the first parameter is global.

So each match begins with { and ends with } and you have 1 capturing parenthesis that matches the content inside the braces. Also since you are using a global match /{([^{}]*)}/g

Therefore, the function is invoked twice on the 2 matches with the following parameters:

  1. '{name}', 'name', 7, 'Hello, {name} welcome to {place}'
  2. '{place}', 'place', 25, 'Hello, {name} welcome to {place}'

and the entire match (ie the first parameter) is replaced with the return value of the function

Upvotes: 0

Chris Like
Chris Like

Reputation: 280

If the maximum number of arguments isn't used, they are ignored. But if the arguments within the function are referenced and not tested first for !undefined, the script will error out.

Upvotes: 0

Blender
Blender

Reputation: 298146

The first parameter is the entire string matched by your regex (capturing groups don't matter, so it becomes {name}).

The second, third, fourth, etc. parameters are your capturing groups and since you only have one, your second argument becomes name.

The last two parameters are the position of the match and the entire string. You can omit these arguments from your callback if you'd like.

Here's a slightly more readable version of your code that accounts for attributes that aren't present in your replacement object:

var replace = function(string, object) {
    return string.replace(/\{(.*?)\}/g, function(match, group) {
        return group in object ? object[group] : match;
    });
};

Demo: http://jsfiddle.net/KeHdU/4/

Upvotes: 1

Related Questions