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