Chris Lercher Chris Lercher - 3 days ago 4x
Javascript Question

Javascript: parseInt() with trailing characters

parseInt("7em", 10);
in all browsers I tested [*]. But can I rely on this?

The reason I ask is, that I want to perform some calculations based on em, like

/* uses em units */ = parseInt(, 10) + 1 + "em";

I could do this with regular expressions, but parseInt is easier to use, and probably a bit faster. Or is there another solution (maybe using jQuery)?

[*] Tested so far on: IE 6, IE 8, Safari 4, Firefox 3.6, Opera 10.5


That is the behavior according to the standard. ECMA-262 section states that

parseInt may interpret only a leading portion of string as an integer value; it ignores any characters that cannot be interpreted as part of the notation of an integer, and no indication is given that any such characters were ignored.

I'd be more worried that at some point in the future the units of will change. In that case, this code could be turning 200px into 200em, which could cause a great deal of confusion.