Search code examples
javascriptmathexponential

javascript expand exponential


Found this function here

http://jsfromhell.com/string/expand-exponential

String.prototype.expandExponential = function(){
return this.replace(/^([+-])?(\d+).?(\d*)[eE]([-+]?\d+)$/, function(x, s, n, f, c){
    var l = +c < 0, i = n.length + +c, x = (l ? n : f).length,
    c = ((c = Math.abs(c)) >= x ? c - x + l : 0),
    z = (new Array(c + 1)).join("0"), r = n + f;
    return (s || "") + (l ? r = z + r : r += z).substr(0, i += l ? z.length : 0) + (i < r.length ? "." + r.substr(i) : "");
});
};

I sort of get the replace part, but I'm lost when I see the function(x,s,n,f,c) part. What am I missing?

Can someone help me break this down into more understandable components?


Solution

  • See this page

    Basically, x is the matched substring. s corresponds to the part that was matched by the first pair of parentheses (([+-])), n corresponds to the part matched by the second parentheses ((\d+)), and so on.

    The matched string is replaced by the value returned by this function.