【问题标题】:Javascript convert string to array with seperate letters and numberJavascript将字符串转换为具有单独字母和数字的数组
【发布时间】:2021-09-01 11:30:19
【问题描述】:

我有一个字符串需要去掉字母和数字。字符串中只有一个数字。

例如这个字符串:

"AM12"我想拆分成这样:

['A','M',12]

最有效的方法是什么?我之前可以用分隔它们的字符串中的破折号(A-M-12)来做到这一点,但被要求删除破折号。

这是我用于破折号的代码: let arrUrl = myString.split('-');

谢谢。

【问题讨论】:

标签: javascript arrays string split


【解决方案1】:

您可以使用/\d+|./。它将匹配连续的数字或单个字符。

const split = str => str.match(/\d+|./g)

console.log(split("AM12"))
console.log(split("Catch22"))

【讨论】:

    【解决方案2】:

    如果您需要数字部分在结果数组中为数字,您可以尝试这样的操作

    let test = 'AM12'
    let res = []
    let num = ''
    test.split('').forEach(e=>isNaN(e)?res.push(e):num+=e)
    res.push(parseInt(num))
    console.log(res)

    【讨论】:

    • 仅供参考:isNaN(" ") 是假的。所以,AM 12 也会返回 ["A", "M", 12]
    【解决方案3】:

    您可以线性扫描输入字符串,逐个字符,并跟踪任何运行数字,还应注意负数。

    以下 sn-p 处理负数以及同一输入中的多个数字。

    function isDigit(char) {
      return char >= "0" && char <= "9";
    }
    
    function split(input) {
      const result = [];
    
      // keep track of the running number if any
      let runningNum = 0;
      let isNum = false;
      let isNegative = false;
    
      for (let i = 0; i < input.length; i++) {
        const ch = input[i];
    
        if (isDigit(ch)) {
          // check for negative value
          if (i > 0 && input[i - 1] === "-") {
            isNegative = true;
          }
    
          runningNum *= 10;
          runningNum += (isNegative ? -1 : 1) * (ch - "0");
          isNum = true;
        } else {
          // push previous running number if any
          if (isNum) {
            result.push(runningNum);
            runningNum = 0; // reset
            isNum = false;
            isNegative = false;
          }
    
          // if current char is a "-" sign and the following char is a digit continue,
          // if not then it's a hyphen
          const isLastChar = i === input.length - 1;
          if (!isLastChar && input[i] === "-" && isDigit(input[i + 1])) {
            continue;
          }
    
          result.push(ch);
        }
      }
    
      // in case the number at the end of the input string
      if (isNum) {
        result.push(runningNum);
      }
    
      return result;
    }
    
    const inputs = ["AM-12", "AM-12-30", "AM-12B30", "30", "a3b", "ab", "-", "-abc", "a-12-"];
    for (let input of inputs) {
      console.log(`"${input}": `, split(input));
    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-01-24
      • 2022-01-23
      • 2017-12-24
      • 2021-01-09
      • 2015-01-03
      • 1970-01-01
      • 2015-11-11
      相关资源
      最近更新 更多