简体   繁体   中英

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

If I have this string

str = "22px";

How do I extract just the number 22? Thanks.

你可以试试 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
  • ([az%]*) .. 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 - ie, 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!

试试这个...

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

但这仅适用于数字始终为 2 位数的情况。

我想你可以去str.substring(0, 2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM