What is parse-unit?
The parse-unit npm package is used to parse CSS units from strings. It extracts the numeric value and the unit from a given string, making it useful for handling and manipulating CSS values programmatically.
What are parse-unit's main functionalities?
Parse CSS Units
This feature allows you to parse a CSS unit string into its numeric value and unit. For example, '10px' would be parsed into 10 and 'px'.
const parseUnit = require('parse-unit');
const [value, unit] = parseUnit('10px');
console.log(value); // 10
console.log(unit); // 'px'
Handle Different Units
This feature demonstrates the ability to handle different types of units such as percentages. For example, '50%' would be parsed into 50 and '%'.
const parseUnit = require('parse-unit');
const [value, unit] = parseUnit('50%');
console.log(value); // 50
console.log(unit); // '%'
Default Unit Handling
This feature shows how the package handles strings without explicit units. For example, '100' would be parsed into 100 and an empty string.
const parseUnit = require('parse-unit');
const [value, unit] = parseUnit('100');
console.log(value); // 100
console.log(unit); // ''
Other packages similar to parse-unit
css-unit-converter
The css-unit-converter package provides similar functionality by converting between different CSS units. It offers more advanced features like unit conversion, which parse-unit does not support.
postcss-value-parser
The postcss-value-parser package is a more comprehensive tool for parsing CSS values. It can parse not only units but also functions, keywords, and more, making it more versatile than parse-unit.
style-value-types
The style-value-types package is part of the Popmotion library and provides utilities for parsing and manipulating CSS values. It offers a broader range of features, including color parsing and value interpolation, which are not available in parse-unit.
parse-unit
Parses a number and unit string, eg "20px"
into [20, "px"]
.
var unit = require('parse-unit')
console.log( unit("50 gold") )
Usage
parse(str[, out])
Parses the string and its unit, returning an array containing the number and unit, separated.
"-20 foo" => [-20, "foo"]
"5.5%" => [5.5, "%"]
5 => [5, ""]
"5" => [5, ""]
This will create a new array unless you specify an array to out
, which allows you to re-use arrays.
License
MIT, see LICENSE.md for details.