开发者

How might I extract the number from a number + unit of measure string using JavaScript?

If I have this string

st开发者_StackOverflow社区r = "22px";

How do I extract just the number 22? Thanks.


You could try str.match(/\d+/);


If you want an actual number, you should try parseInt(). It will take care of taking off the 'px' for you.

str = "22px";

num = parseInt(str, 10); // pass in the radix for safety :)

assert(num === 22);


Here's a regex that splits the value from the unit. It also works with negative values and decimal numbers:

str.match(/(-?[\d.]+)([a-z%]*)/)

Regex explained:

  • (-?[\d.]+) .. Grabs an optional "-" followed by digits or dots
  • ([a-z%]*) .. Finds all letters or % signs that directly follow the number

Here's a sample function that returns the specific parts:

function parseVal(str) {
    res = str.match(/(-?[\d.]+)([a-z%]*)/);
    return {
        val: parseFloat(res[1]),
        unit: res[2]
    }
}

parseVal( '12px' )               // { val: 12, unit: 'px' }
parseVal( '-20.5%' )             // { val: -20.5, unit: '%' }
parseVal( '22.75em' )            // { val: 22.75, unit: 'em' }
parseVal( '1234' )               // { val: 1234, unit: '' }
parseVal( 'margin-top: -50px;' ) // { val: -50, unit: 'px' }

The last example above shows how "smart" the regex is: It ignores all non-numeric values at the beginning and excess characters at the end - i.e., margin-top: and ; are stripped off

Note

The regex is quite simple. When it receives invalid values it will return unexpected results:

parseVal("...")           // { val: NaN, unit: "" }
parseVal("2.3.4.5pxpxpx") // { val: 2.3, unit: "pxpxpx" }
parseVal("dummy")         // TypeError!


Try this...

parseInt("22px");


"22px".substring(0,2); // returns "22"

But this only works if the number has always 2 digits.


I think you can just go str.substring(0, 2).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜