niken
niken

Reputation: 2611

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?

Upvotes: 0

Views: 375

Answers (2)

Sirko
Sirko

Reputation: 74036

You can pass a function as the second parameter of a replace() call.

The parameter list (from MDN):

  • the matches substring - in your case x
  • the n parenthesized submatch strings - in your case 2: s and n
  • offset of the matched substring - in your case f
  • the total string - in your case c

Upvotes: 1

Manishearth
Manishearth

Reputation: 16188

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.

Upvotes: 1

Related Questions