Javascript: parseInt () with trailing characters

parseInt("7em", 10);

returns 7

in all browsers you tested [*]. But can I rely on this?

I am asking that I want to do some em based calculations like

/* elem1.style.top uses em units */
elem2.style.top = parseInt(elem1.style.top, 10) + 1 + "em";

      

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

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

+2


a source to share


5 answers


This behavior is in accordance with the standard. Section 15.1.2.2 of ECMA-262 states that

parseInt can only interpret the leading part of a string as an integer value; it ignores any characters that cannot be interpreted as being part of an integer notation, and it does not indicate that any such characters were ignored.



I would be more concerned that the units elem2.style.top

will change at some point in the future . In this case, this code can convert 200px

to 200em

, which can cause a lot of confusion.

+5


a source


Yes, you can rely on this. Go to http://www.ecma-international.org/publications/files/ECMA-ST-ARCH/ECMA-262,%203rd%20edition,%20December%201999.pdf and find section '15 .1.2.2 ', parseInt



+1


a source


why not save the road with

parseInt(elem1.style.top.replace(/em/, ""), 10);

      

+1


a source


Yes. You can rely on it.

0


a source


parseInt("7em", 10);

will always return 7, yes. parseInt () returns the first value in the string.

And yes, parseInt is faster and easier to use than regular expressions.

And, if you are using jQuery ? It will not help you in calculation or analysis in this matter, but of course your other code will probably be simpler and better.

http://www.w3schools.com/jsref/jsref_parseInt.asp

0


a source







All Articles