【问题标题】:how to split a string with anything that is not a number如何用非数字的任何东西分割字符串
【发布时间】:2022-01-19 07:32:51
【问题描述】:

字符串输入:

“12个苹果,3个橙子,10个葡萄”

解决方案:

let arr= inputString.split(" ");

要解决的问题:

我将如何与不是数字的任何东西分开?

字符串示例:

  • 没有空格

    • 12apples,3oranges,10grapes
  • () 中的数字

    • there are some (12) digits 5566 in this 770 string 239(我只想要 12、5566、770、239)
  • 对它们进行数学运算的数字串

    • 33+22(应该分成33和22)

我认为可行的方法:

arr= inputString.split("isNaN");

【问题讨论】:

标签: javascript split


【解决方案1】:

你可以使用正则表达式:

const str = '12apples,3oranges,10grapes';

const splitString = str.match(/(?:\d+\.)?\d+/g);

console.log(splitString);

【讨论】:

  • 我认为提问者想要解析输入字符串中的数字数组。
  • 是的。感谢您的澄清。我修改了代码以反映这一点。
【解决方案2】:

let str = "12apples,3oranges,10grapes"

console.log(str.split(/[^\d]/g).filter(e => e))

str = "there are some (12) digits 5566 in this 770 string 239"

console.log(str.split(/[^\d]/g). filter(e => e))

str="33+22"

console.log(str.split(/[^\d]/g). filter(e => e))

【讨论】:

    【解决方案3】:
    let str = "12 apples, 3 oranges, 10 grapes"
    let arr = str.match(/\d+(.\d+)?/g)
    console.log(arr)
    

    【讨论】:

      猜你喜欢
      • 2017-05-14
      • 2016-05-15
      • 1970-01-01
      • 2020-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-19
      相关资源
      最近更新 更多