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);
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:
Demo: http://jsfiddle.net/KeHdU/4/