正则表达式允许在JavaScript中使用负值和十进制值

时间:2019-06-14 09:15:20

标签: javascript regex

我只允许四个小数点后跟数字,并且可以允许负数。

$(document).on("keyup", "input[name='measuredqty']", function(){
  if (/\D/g.test(this.value)){
    this.value = this.value.match(/^-\d+\.?\d{0,4}/);   
  }
});

1 个答案:

答案 0 :(得分:1)

此正则表达式应执行您想要的操作:

var source = {
  "first" : "1",
  "second" : {
     "third" : "3",
     "fourth" : "4"
  },
  "fifth" : [
     {
        "index" : 0,
        "value": "something"
     },
     {
        "index" : 1,
        "value": "else"
     }
  ]
};

var destination = {};

var path = "second.fourth";

_.set(destination, path, _.get(source, path));

path = "fifth[0]";     //Drawback -> if use fifth[1], then destination.fifth will have 0th element empty and 1st element filled.

_.set(destination, path, _.get(source, path));

  • /^-?\d+(\.\d{0,4})?$/ 强制从字符串的开头开始
  • ^允许可选的减号
  • -?允许一个或多个数字
  • \d+说小数部分是可选的,最多4位数字
  • (\.\d{0,4})?强制在字符串末尾完成