开发者

javascript/jquery: quick way to retrieve numeric from length attributes

开发者 https://www.devze.com 2023-02-13 19:22 出处:网络
I have attributes which denotes \"5 px\", \"8px\" \"6em\" and possible some others which I currently cannot think of right now.

I have attributes which denotes "5 px", "8px" "6em" and possible some others which I currently cannot think of right now. I'm interested in only the numeric value (ie 5, 8 or 6.) I kn开发者_运维百科ow i can do some regex but I'm wondering is there a short, documented, cross browser and readable jquery / javascript function out there which already provides this?

regards, Jeroen.

PS not sure if the wording in the title is correct please advice for alternatives.


Use parseInt function:

var str = '5px';
alert(parseInt(str, 10));   // 5

Note that second argument of 10 represents base 10 there.


In case they ever come back as 08px, (leading zero), use the radix of 10. Otherwise parseint() thinks your number is in octal.

var value = parseInt(str, 10);

It is probably never going to happen being returned from jQuery as a CSS property value, but a good habit to get into.


A combination of parseInt/parseFloat (see the other answers) is probably your best bet, but just for kicks (and if you want to make your code completely unreadable), you can always use a Regex with extra cheese:

+(str.match(/(-?\d+(?:\.\d+)?)/)||[,0])[1]

The + operator converts the result to a Number, ||[,0] provides a default array if there's no number in str. [,0] might not work in all browsers, but [0,0] will.

:)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号