如何可靠地找到 javascript 中的分数和小数
How do I reliably find fractions and decimals in javascript
Q) 我希望能够在 js 中解析字符串并输出字符串中的数字或分数部分。
例如:"1.5 litres 1/4 cup"
注意:我已经想出了如何从下面的示例字符串中获取整数和小数,但不是分数表示。
我目前正在使用这样的东西:
const originalString = "1.5 litres 1/4 cup";
var number_regex = /[+-]?\d+(\.\d+)?/g;
var matches = [];
var match;
// FIX - does this ever actually get stuck ?
// replace this with non-while loop from article: http://danburzo.ro/string-extract/
while ((match = number_regex.exec(originalString)) !== null) {
matches.push({
original: match[0],
newVal: ''
});
}
console.log(matches)
您可以使用它来提取每个数字作为字符串数组
const input = `Take 1.5 litres 1/4 cup of sugar
and 2ml or 2/3 teaspoon or salt
then take 5 litres of 2.5% vinegar`
const regex = /[+-]?\d+(?:[\.\/]?\d+)?/gm
console.log(
[...input.matchAll(regex)].map(a => a[0])
)
// returns ["1.5", "1/4", "2", "2/3", "5", "2.5"]
Q) 我希望能够在 js 中解析字符串并输出字符串中的数字或分数部分。
例如:"1.5 litres 1/4 cup"
注意:我已经想出了如何从下面的示例字符串中获取整数和小数,但不是分数表示。
我目前正在使用这样的东西:
const originalString = "1.5 litres 1/4 cup";
var number_regex = /[+-]?\d+(\.\d+)?/g;
var matches = [];
var match;
// FIX - does this ever actually get stuck ?
// replace this with non-while loop from article: http://danburzo.ro/string-extract/
while ((match = number_regex.exec(originalString)) !== null) {
matches.push({
original: match[0],
newVal: ''
});
}
console.log(matches)
您可以使用它来提取每个数字作为字符串数组
const input = `Take 1.5 litres 1/4 cup of sugar
and 2ml or 2/3 teaspoon or salt
then take 5 litres of 2.5% vinegar`
const regex = /[+-]?\d+(?:[\.\/]?\d+)?/gm
console.log(
[...input.matchAll(regex)].map(a => a[0])
)
// returns ["1.5", "1/4", "2", "2/3", "5", "2.5"]