Skip to main content
Stack Overflow
  1. About
  2. For Teams

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Required fields*

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

Answer*

Draft saved
Draft discarded
Cancel

lang-js

AltStyle によって変換されたページ (->オリジナル) /