【问题标题】:How do I reliably find fractions and decimals in javascript如何在javascript中可靠地找到分数和小数
【发布时间】:2026-01-09 22:25:01
【问题描述】:

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)

【问题讨论】:

  • 请重新打开这个 - 我已经添加了我当前的代码 - 不要这么快判断。
  • 你的正则表达式从来没有尝试匹配正斜杠......你应该尝试一些东西,至少......看起来你没有做任何事情来进行额外的匹配,然后离开由我们决定。 downvote 按钮有一个关于此的工具提示...
  • \. 更改为[.\/]

标签: javascript regex string typescript fractions


【解决方案1】:

您可以使用它来将每个数字提取为字符串数组

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"]

【讨论】: