stripUnit.js.flow 634 B

12345678910111213141516171819202122232425262728
  1. // @flow
  2. const cssRegex = /^([+-]?(?:\d+|\d*\.\d+))([a-z]*|%)$/
  3. /**
  4. * Returns a given CSS value minus its unit of measure.
  5. *
  6. * @example
  7. * // Styles as object usage
  8. * const styles = {
  9. * '--dimension': stripUnit('100px')
  10. * }
  11. *
  12. * // styled-components usage
  13. * const div = styled.div`
  14. * --dimension: ${stripUnit('100px')};
  15. * `
  16. *
  17. * // CSS in JS Output
  18. *
  19. * element {
  20. * '--dimension': 100
  21. * }
  22. */
  23. export default function stripUnit(value: string | number): string | number {
  24. if (typeof value !== 'string') return value
  25. const matchedValue = value.match(cssRegex)
  26. return matchedValue ? parseFloat(value) : value
  27. }