【问题标题】:Extracting a Numbers from a String in JavaScript [duplicate]从 JavaScript 中的字符串中提取数字 [重复]
【发布时间】:2022-11-23 10:51:08
【问题描述】:

我想从字符串中提取数字。 (例如,我想要来自字符串24:38024380)我想将它分配给相应的变量。有什么办法可以做到吗?

我找不到解决这个问题的方法。

【问题讨论】:

  • "24:380".split(":").map(Number)
  • 你试过split()了吗?还需要有关您的问题的更多详细信息
  • 哦,我会试试这个。
  • 如何将其分配给相应的变量?
  • 的一般解决方案提取(与按分隔符拆分相反)将是 ("24:380".match(/\d+/gu) ?? []).map(Number)。然后你得到一个数组。如何分配取决于上下文。 const [ first, last ] = ("24:380".match(/\d+/gu) ?? []).map(Number); 将是一种方法。

标签: javascript string numbers extract


【解决方案1】:

你可以使用RegEx

const paragraph = 'The quick brown 45 jumps over the lazy 23:12. It barked.';
const regex = /(d+)/g;
const found = paragraph.match(regex);

console.log(found);
// expected output: Array ["45", "23", "12"]

【讨论】:

    【解决方案2】:

    拆分,映射到数字,并使用数组解构进行分配。

    const [first, second] = "23:380".split(":").map(Number);
    

    【讨论】:

      【解决方案3】:

      使用正则表达式匹配:

      const str = '24:380';
      const regex = /24|380/g
      const resultArr = str.match(regex);
      for (const output of resultArr) console.log(output);
      // output:
      // 24
      // 380

      【讨论】:

        猜你喜欢
        • 2018-08-30
        • 1970-01-01
        • 1970-01-01
        • 2018-12-14
        • 2019-06-17
        • 2017-02-17
        • 2017-07-20
        • 2012-01-12
        • 1970-01-01
        相关资源
        最近更新 更多