【发布时间】:2020-11-17 17:09:06
【问题描述】:
字符串看起来像3*2.2或6+3.1*3.21或(1+2)*3,1+(1.22+3)或0.1+1+2.2423+2.1这样的东西,它可能会有所不同。我必须找到string 内小数位数最多的数字的小数位数。
我完全不知道该怎么做
【问题讨论】:
标签: javascript string function char string-search
字符串看起来像3*2.2或6+3.1*3.21或(1+2)*3,1+(1.22+3)或0.1+1+2.2423+2.1这样的东西,它可能会有所不同。我必须找到string 内小数位数最多的数字的小数位数。
我完全不知道该怎么做
【问题讨论】:
标签: javascript string function char string-search
您可以使用正则表达式查找所有有小数位的数字,然后使用Array.prototype.reduce 查找最多的小数位数。
const input = '0.1+1+2.2423+2.1';
const maxNumberOfDecimalPlaces = input
.match(/((?<=\.)\d+)/g)
?.reduce((acc, el) =>
acc >= el.length ?
acc :
el.length, 0) ?? 0;
console.log(maxNumberOfDecimalPlaces);
请注意,当在字符串中找不到带小数位的数字时,这将返回 0。
【讨论】:
你可以使用正则表达式模式
var str="6+3.1*3.21"
d=str.match(/(?<=\d)[.]\d{1,}/g)
d!=null ? res=d.map((n,i) => ({["number" + (i+1) ] : n.length - 1}))
: res = 0
console.log(res)
【讨论】:
您可以执行以下操作:
Array.prototype.split()你的输入字符串通过正则表达式/\[^\d.\]+/提取数字Array.prototype.map() 遍历生成的数字数组,并通过小数分隔符将它们分成whole 和fractional 部分,返回小数部分的length 或0(对于整数)Math.max() 查找最大值length
上述方法似乎更健壮,因为它不涉及某些不受支持的功能:
/(?<=)/) which may not be supported 通过某些流行的浏览器,如 Safari 或 Firefox(低于当前版本).?) 或nulish coalescing (??)
const src = ['3*2.2', '6+3.1*3.21', '(1+2)*3' , '1+(1.22+3)', '0.1+1+2.2423+2.1'],
maxDecimals = s =>
Math.max(
...s
.split(/[^\d.]+/)
.map(n => {
const [whole, fract] = n.split('.')
return fract ? fract.length : 0
})
)
src.forEach(s => console.log(`Input: ${s}, result: ${maxDecimals(s)}`))
.as-console-wrapper{min-height:100%;}
【讨论】:
fract 变量包含浮点数的小数部分,它使用非常基本的 RegExp,这比后向断言更容易理解,其余部分非常基本的.split() 和.map(),所以如果您认为除了更强大之外(因为其他两种解决方案在某些流行的浏览器中可能根本失败)我当前解决方案更全面,请随时重新接受。