gpt4 book ai didi

javascript - JS - 如何验证字符串是否为数字

转载 作者:行者123 更新时间:2023-11-30 20:29:13 25 4
gpt4 key购买 nike

我尝试验证各种输入字符串。因此我尝试使用正则表达式。不幸的是,所有否定案例也都匹配为真。如何确定正则表达式必须匹配整个字符串?

const regex = /(^([0-9]+(.||,)+[0-9]?)$)||(^([0-9]+)$)||(^(.||,)+[0-9]+$)/;

const testSetPositiv = ["34", "45.45", ".7867", "3434,34", ",7834", "546.", "45546,", "0"]

const testSetNegativ = ["wegrger", "3443,34erf", "3443.34erf", ",", ".", "4525tg", "1,211.23", "1.211,23"]


testSetPositiv.forEach(function(value) {
console.log(regex.test(value));
//should always return true
})
console.log("----------------");

testSetNegativ.forEach(function(value) {
console.log(regex.test(value));
//should always return false
})


我也尝试使用 parseFloat(...),但它接受例如 "5.45abc":

const testSetPositiv = ["34", "45.45", ".7867", "3434,34", ",7834", "546.", "45546,", "0"]

const testSetNegativ = ["wegrger", "3443,34erf", "3443.34erf", ",", ".", "4525tg", "1,211.23", "1.211,23"]


testSetPositiv.forEach(function(value) {
console.log(parseFloat(value) >= -Number.MAX_VALUE)
//should always return true

})
console.log("----------------");

testSetNegativ.forEach(function(value) {
console.log(parseFloat(value) >= -Number.MAX_VALUE)

//should always return false
})

最佳答案

一个简单的正则表达式解决方案:

const regex = /^(\d*[.,]?\d+|\d+[.,]?\d*)$/;

const testSetPositiv = ["34", "45.45", ".7867", "3434,34", ",7834", "546.", "45546,", "0"]

const testSetNegativ = ["wegrger", "3443,34erf", "3443.34erf", ",", ".", "4525tg", "1,211.23", "1.211,23"]



testSetPositiv.forEach(function(value) {
console.log(regex.test(value));
//should always return true
})
console.log("----------------");

testSetNegativ.forEach(function(value) {
console.log(regex.test(value));
//should always return false
})

关于javascript - JS - 如何验证字符串是否为数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50544790/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com