【问题标题】:How can I add one word to another word in a string to an array in Javascript? [duplicate]如何将一个单词添加到字符串中的另一个单词到Javascript中的数组? [复制]
【发布时间】:2020-09-12 03:28:19
【问题描述】:

我有一个类似这样的字符串:

apples1h7s5e47epearshrrdjhrdjdrjapples15r4h775h47pearshrmbaewv4kg0kapples15hrs477sr547pears

我想从字符串中获取所有从苹果到梨的单词并将它们放入一个数组中。 所以输出将是:

apples1h7s5e47epears, apples15r4h775h47pears, apples15hrs477sr547pears

【问题讨论】:

  • 抱歉,重复关闭者,当您按下按钮时,您是否阅读过“标记重复”的问题和内容?这是无稽之谈!!他没有问'如何用正则表达式找到东西'!请多加注意。

标签: javascript arrays node.js string


【解决方案1】:

我建议先将字符串解析为字符数组,然后查找单词组合并将它们添加到您定义的另一个数组中。这可能是最直接的方法,但可能有更简单的方法,我主要使用 C#,所以我不确定。

【讨论】:

    【解决方案2】:

    在这里我将其拆分,然后过滤。

    请记住,这在 IE 中不起作用,您需要一个 Polyfill

    let bigString = "apples1h7s5e47epears hrrdjhrdjdrj apples15r4h775h47pears hrmbaewv4kg0k apples15hrs477sr547pears";
    
    let result = bigString.split(" ").filter(el => el.startsWith("apples") && el.endsWith("pears"))
    
    console.log(result);

    startsWithPolyfill:

    if (!String.prototype.startsWith) {
      String.prototype.startsWith = function(searchString, position) {
        position = position || 0;
        return this.indexOf(searchString, position) === position;
      };
    }
    

    endsWithPolyfill:

    if (!String.prototype.endsWith) {
      String.prototype.endsWith = function(searchString, position) {
          var subjectString = this.toString();
          if (typeof position !== 'number' || !isFinite(position) || Math.floor(position) !== position || position > subjectString.length) {
            position = subjectString.length;
          }
          position -= searchString.length;
          var lastIndex = subjectString.indexOf(searchString, position);
          return lastIndex !== -1 && lastIndex === position;
      };
    }
    

    【讨论】:

    • 差不多 - 要求是“以苹果开头,以梨结尾”
    • @AndreasDolk 答案已更新,我想现在应该可以工作了...
    【解决方案3】:

    您可以为此使用正则表达式

    const string = "apples1h7s5e47epears hrrdjhrdjdrj apples15r4h775h47pears hrmbaewv4kg0k apples15hrs477sr547pears"
    
    const data = string.match(/(apples\w*)/g)
    console.log(data)
    

    我希望这可能会有所帮助

    【讨论】:

      猜你喜欢
      • 2022-01-14
      • 2020-09-01
      • 2021-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-05
      • 1970-01-01
      相关资源
      最近更新 更多