Frage

I'm parsing an XML document with JS, changing to lower case every first letter of the tags names. I.E. <MyTagName></MyTagName> will become <myTagName></myTagName>, very simple and everything works fine. I'm using a regex to find all the tags and replacing the name with the camel version, like this:

regex = /(<)(\/){0,1}([A-Z]*)(\/){0,1}(>)/ig;

result = result.replace(regex, function(s, m0, m1, m2, m3, m4){
    return m0 + (m1 ? m1 : "") + camelNotation(m2) + (m3 ? m3 : "") + m4;
});

My question is: is there a way to get some of the parameters in the anonymous function which is the second argument of my replace function in a more dynamic way, like an array? Something like

result = result.replace(regex, function(s, param[]){
    return param[0] + (param[1]? param[1] : "") + camelNotation(param[2]) + (param[3] ? param[3] : "") + param[4];
});

I may use arguments[i], but I would like to know if I can customize my parameters in the function signature.

Thank you

War es hilfreich?

Lösung

I often use the following simple higher-order function:

splat = function(fun, thisp) {
    return function() { return fun.call(thisp, [].slice.call(arguments)) }
}

e.g.

"a1b2c3d4e5f6".replace(/(\D)(\d)/g, splat(function(a) {
    return a[1].toUpperCase() + (++a[2]);
}))

Andere Tipps

You can use a forwarding function to package up the arguments into an array:

result.replace(regex, function(s) {
    return realFunction(s, Array.prototype.slice.call(arguments, 1));
});

where realFunction has the signature function(s, params) (it can of course be defined and called inline if you prefer). See the documentation on arguments for info on how this works.

You can grab the arguments inside the body of the function like so:

result = result.replace(regex, function(s, /*params...*/){
  // get real array without the first argument
  var params = [].slice.call(arguments, 1);
  ...
});

I may use arguments[i], but I would like to know if I can customize my parameters in the function signature.

You can use arguments or get the arguments you want into an array, but other than that there's no alternative syntax (yet, it's coming soon). The convention for "rest params" is to annotate them as a comment.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top