【问题标题】:Remove all alphabetical characters and leading zeros from strings in an array with JavaScript使用 JavaScript 从数组中的字符串中删除所有字母字符和前导零
【发布时间】:2021-02-06 20:38:11
【问题描述】:

感谢您花时间阅读我的问题。

我需要从数组中的字符串元素中删除所有字母字符和前导零。数组看起来像这样:

["DE73456","DE71238","FR00034","FR00036","ES00038","US00039","DE00098", ...]

结果应该是以下整数数组:

[73456,71238,34,36,38,39,98, ...]

最后,我想从这个数字升序排序列表中确定最小的省略值​​trong>。我已经找到了一个 JS 函数,它可以通过传递一个整数数组来完成这项工作 - 它可以按需要完美地工作。

也许我们可以通过某种方式将上述要求与下面的 JS 函数结合起来,以确定最小的省略值。

var k = [73456,71238,34,36,38,39,98];

k.sort(function(a, b) { return a-b; });   // To sort by numeric

var offset = k[0];
var lowest = -1;
for (i = 0;  i < k.length;  ++i) {
  if (k[i] != offset) {
    lowest = offset;
    break;
  }
  ++offset;
}
if (lowest == -1) {
    lowest = k[k.length - 1] + 1;
}
return lowest;

所以,简而言之,我想从字符串数组中确定最低省略值​​trong>。

["DE73456","DE71238","FR00034","FR00036","ES00038","US00039","DE00098", ...]

因此,对于上述示例,JS 函数的 result 应该返回 35。

非常感谢您的建议!我期待着阅读您的 cmets。

【问题讨论】:

  • 如果您从字符串中删除所有字符,则该字符串将为空。我认为您的意思是“字母字符”?
  • 你是对的@JoelFan,在这方面的问题没有很好地说明。我已经编辑了这个问题 - 感谢您指出这一点!

标签: javascript arrays regex string data-manipulation


【解决方案1】:

您可以使用这个简单的正则表达式替换:

repl = str.replace(/^[a-zA-Z]+0*/, "")

RegEx Demo

正则表达式详细信息:

  • ^:开始
  • [a-zA-Z]+: 匹配一个字母
  • 0*:匹配零个或多个0s
  • 替换只是一个空字符串

【讨论】:

    【解决方案2】:

    您还可以使用单个字符类 ^[A-Z0]+ 匹配 1 次或多次出现的 A-Z 或字符串 ^ 开头的 0,然后使用数组映射。

    s = s.replace(/^[A-Z0]+/, "")
    

    const a = ["DE73456", "DE71238", "FR00034", "FR00036", "ES00038", "US00039", "DE00098"];
    console.log(a.map(s => s.replace(/^[A-Z0]+/, "")))

    【讨论】:

    • 非常感谢!合并后的代码实际上完成了这项工作。 const a = ["DE73456", "DE71238", "FR00034", "FR00036", "ES00038", "US00039", "DE00098"]; console.log(a.map(s =&gt; s.replace(/^[A-Z0]+/, ""))) var k = a.map(s =&gt; s.replace(/^[A-Z0]+/, "")); k.sort(function(a, b) { return a-b; }); // To sort by numeric var offset = k[0]; var lowest = -1; for (i = 0; i &lt; k.length; ++i) { if (k[i] != offset) { lowest = offset; break; } ++offset; } if (lowest == -1) { lowest = k[k.length - 1] + 1; } console.log("Lowest = " + lowest);
    【解决方案3】:

    您也可以使用match 而不是删除不需要的字符。

    str = "FR00034"
    str.match(/[1-9][0-9]*/)
    

    正则表达式详细信息:

    • [1-9]: 第一个字符应该是非零数字
    • [0-9]*:以下所有数字

    获得最低值的最终函数应该如下所示。

    function getLowestOf() {
        const numbers = arr.map((item) => Number(item.match(/[1-9][0-9]*/)[0]));
        const sorted = numbers.sort((a, b) => a - b);
        // console.log(sorted);
        return sorted[0];
    }
    const arr = ["DE73456","DE71238","FR00034","FR00036","ES00038","US00039","DE00098"];
    console.log(getLowestOf(arr))

    【讨论】:

      【解决方案4】:

      对于提供的列表示例,regular expression like ... (/^[0\D]+/) ... 已经足够用于字符串replacement。由于该任务以及casting a string into a number value 的附加任务必须针对每个数组项进行处理,因此需要使用Array.prototype.map。

      为了达到 OP 所希望的最终结果,必须实现一个函数,该函数从整数的无序列表中获取最小的省略值 ...

      const sampleList = ["DE73456","DE71238","FR00034","FR00036","ES00038","US00039","DE00098"];
      
      // for the above samples a regex like ... /^[0\D]+/ ... already
      // is sufficient enough ... [https://regex101.com/r/ZSDGvC/1/]
      
      // an unsorted list of integers ...
      console.log(
        sampleList
          .map(sample => Number(sample.replace((/^[0\D]+/), '')))
      );
      
      
      function getLowestOmittedValueFromIntegerList(list) {
        let lowestOmittedInteger;
        let hasOmittedValue = false;
      
        const maximumListCount = (list.length - 1);
      
        // use shallow copy for not mutating the original
        // ... and sort this new array in ascending order.
        list = Array.from(list).sort((a, b) => (a - b));
      
        // look for omitted value, save it and exit early.
        list.some((integer, idx) => {
      
          if (idx < maximumListCount) {
            if ((integer + 1) < list[idx + 1]) {
      
              lowestOmittedInteger = (integer + 1);
              hasOmittedValue = true;
            }
          }
          return hasOmittedValue;
        });
      
        return lowestOmittedInteger;
      }
      
      // the lowest omitted value from an unsorted list of integers ...
      console.log(
        getLowestOmittedValueFromIntegerList(
          sampleList
            .map(sample => Number(sample.replace((/^[0\D]+/), '')))
        )
      );
      
      // proof of concept ...
      console.log('\nproof of concept ...\n\n');
      
      console.log( // expect the undefined value
        getLowestOmittedValueFromIntegerList([9,8,7,6,6,6,5,4,3,2,1,0])
      );
      console.log( // expect 7 
        getLowestOmittedValueFromIntegerList([9,8,6,6,6,5,4,3,2,1,0])
      );
      
      console.log( // expect 11
        getLowestOmittedValueFromIntegerList([0,1,2,3,4,5,6,7,8,9,10,12])
      );
      console.log( // expect the undefined value
        getLowestOmittedValueFromIntegerList([0,1,2,3,4,5,6,7,8,9,10,11,12])
      );
      
      console.log( // expect -1
        getLowestOmittedValueFromIntegerList([-4,-3,-2,0,1,2,3,4])
      );
      console.log( // expect -2
        getLowestOmittedValueFromIntegerList([-4,-3,-1,0,1,2,3,4])
      );
      .as-console-wrapper { min-height: 100%!important; top: 0; }

      【讨论】:

      • 谢谢彼得。但是,我正在寻找结果整数数组范围内的最低 unused 数字。感谢您的帮助。
      • @nairolf ...所提供的示例是哪个?..从您的解释中不太清楚。会不会是36,因为这个数字序列没有出现在所有其他提取的数字中?
      • 它将是 35。如果您查看字符串数组的这一部分,35 将是生成的整数数组范围内的最小未使用数字。 ["FR00034","FR00036","ES00038","US00039"]
      • 这是... "从数字的升序排序列表中获取最小的省略值" ...范围有所不同...无论如何我已经正在努力...
      • 感谢您的澄清和帮助。非常感谢!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-06-25
      • 2017-07-10
      • 1970-01-01
      • 2022-01-09
      • 2011-04-09
      • 2015-09-11
      • 2018-08-14
      相关资源
      最近更新 更多