【问题标题】:Concat array values连接数组值
【发布时间】:2019-06-12 22:07:20
【问题描述】:

我有这个字符串:

Item 1Item 2Item 3Item 4

我想得到:

["Item 1", "Item 2", "Item 3", "Item 4"]

我试过这样做:

var string = 'Item 1Item 2Item 3Item 4'
var regex = string.split(/(\d)/)
regex.splice(-1, 1)
regex[regex.length - 2] += regex[regex.length - 1];
regex.splice(-1, 1)
console.log(regex);

但它不起作用,知道如何获得所需的结果吗?

编辑:

max 处的字符串可能如下所示:

Item 1Item 2Item 3Item 4Item NItem N-1

【问题讨论】:

  • But I rather got :But I'd rather get:?
  • 这是唯一需要处理的字符串还是有更多情况?
  • @treyBake 很抱歉造成混乱 - 将问题更新为更清晰。
  • 使用string.split(/(?!^)(?=Item)/)
  • @JamesCoyle 更新了答案以添加另一个示例。

标签: javascript arrays regex


【解决方案1】:

注意:答案处理原始情况 - 更新前

使用String.match() 查找以数字序列(regex101)结尾的非数字序列:

var string = 'Item 1Item 2Item 3Item 4'
var arr = string.match(/\D+\d+/g)
console.log(arr);

【讨论】:

  • \d -> \d+ 更好
  • 如果字符串看起来像这样Item 1Item 2Item 3Item 4Item NItem N-1?
  • @IslamElshobokshy 澄清一下,您实际上在您的字符串中有"Item N""Item N-1",还是"N""N-1" 只是一个占位符任意的数字序列。 (在讨论正则表达式时,您需要使用非常精确的语言)。
  • @p.s.w.g 它们实际上是字符串,否则我会提到它,但你说得对,我需要澄清一下。
  • 我看过,但是我给出的另一个例子有字符串Item NItem N-1,它们不是数字^^所以我可以使用/\D+|N+|N\-1+/g吗?
【解决方案2】:

如果你的elements 总是以Item 开头,你可以使用split() 来做这样的事情:

const str = 'Item 1Item 2Item 3Item 4Item N-2Item N-1Item N'
var arr = str.split("I").slice(1).map(x => "I" + x);
console.log(arr);

甚至更好,或者您可以使用 match() 使用单个正则表达式来完成它

const str = 'Item 1Item 2Item 3Item 4Item 999Item N-2Item N-1Item N'
var arr = str.match(/Item\s[1-9|N|-]+/g);
console.log(arr);

【讨论】:

    【解决方案3】:

    要达到预期的效果,请使用以下带有替换、拆分和切片的选项

    1. 使用替换在“I”之前添加双空格
    2. 使用 split(' ') 以双倍空格分割
    3. 使用 slice(1) 删除第一个空字符串

    var str = "Item 1Item 2Item 3Item 4Item NItem N-1"
    
    let arr = str.replace(/\I/g, '  I').split('  ').slice(1);
    
    console.log(arr)

    codepen - https://codepen.io/nagasai/pen/qLzKwJ?editors=1010

    【讨论】:

      【解决方案4】:

      当您在传递给.split 的正则表达式中有一个捕获组 ((...)) 时,捕获的文本将作为结果的一部分返回。这就是为什么在"Item " 之间有"1""2" 等。

      除了@Ori Dori's solution 的一些变体之外,您还可以使用lookahead assertion (?=...) 来解决这个问题,这是一个非捕获构造。

      var string = 'Item 1Item 2Item 3Item 4Item NItem N-1';
      var arr = string.split(/(?=Item)/);
      console.log(arr);

      这将通过在文本 "Item" 出现之前立即拆分字符串来实现。


      对于完全不使用正则表达式的更暴力解决方案:

      var string = 'Item 1Item 2Item 3Item 4Item NItem N-1';
      var arr = [];
      var i = string.indexOf('Item', 1);
      while (i >= 0) {
        arr.push(string.substr(0, i));
        string = string.substr(i);
        i = string.indexOf('Item', 1);
      }
      arr.push(string);
      console.log(arr);

      【讨论】:

        猜你喜欢
        • 2021-10-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-10-13
        • 2020-12-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多