带小数和单位的负值/正值

问题描述 投票:0回答:2

我正在寻找一个输入字段,它只接受带有小数的负值/正值和输入结束时预定义的(在数组中)单位。

可接受的样本值为:

var inputValue = "150px"; <---- This could be anything (from the input).
var units = ["px", "em", "%"];
var defaultUnit = "px";


100px, 100em, 100%
-100px, -100em, -100%
-100.50px, -100.50em, -100.50%

最后,我需要将“单位”和值保存在变量中。如果用户没有提供单位I,那么我应该将默认值(px)指定为单位。

var value = 100;
var unit = %;

我想不出用纯javascript或ES15方式做所有这些的方法。谁能指导我?

javascript html arrays validation vue.js
2个回答
0
投票

使用正则表达式

const rx = /(-?[\d\.]+)(.*)/

//Group 1. optional negative sign, then digits or digits.digits
//Group 2. unit

const data = ['10px', '11.12in', '-4%']

data.forEach(it => {
  const m = rx.exec(it)
  if (m) {
    const parsed = {
      value: parseFloat(m[1]),
      unit: m[2]
    }     
    console.log(it, parsed)
  }
})

您可以固定正则表达式以拒绝多个.字符,但这是一个简单的演示。 parseFloat函数也会捕获它。


1
投票

使用regex match operation可以这样做:

function splitToValueAndUnit(string) {
  if(!string) {
    return { value: "", unit: "px" };
  }
  string = string.toString();
  var value = string.match(/[+-]?\d*[.]?\d*/)[0];
  var unit = string.replace(value, "")
  return {
    value: value,
    unit: unit || "px"
  }
}



console.log(splitToValueAndUnit("123px"))
console.log(splitToValueAndUnit("123%"))
console.log(splitToValueAndUnit("123"))
console.log(splitToValueAndUnit("-123"))
console.log(splitToValueAndUnit("-123px"))
console.log(splitToValueAndUnit("-123.099%"))
console.log(splitToValueAndUnit(""))
console.log(splitToValueAndUnit())
console.log(splitToValueAndUnit(123))
console.log(splitToValueAndUnit(undefined))
© www.soinside.com 2019 - 2024. All rights reserved.