【问题标题】:JavaScript - Check if string contain two strings next to each other from array and insert string in betweenJavaScript - 检查字符串是否包含数组中相邻的两个字符串并在其间插入字符串
【发布时间】:2018-07-25 14:51:55
【问题描述】:

我想检测一个数组中是否有两个字符串在一个数组中的每一个旁边,然后在其间插入另一个字符串。
因此,如果我的数组包含 ["hello", "there", "hi"] 并且我检查了这个字符串 "hellothere",它会在其间插入字符串 " ",因此它最终会成为 "hello there"。如果我有两个相同的单词相邻,这也应该适用。

我的问题是,我不知道如何检查一个字符串是否包含数组中彼此相邻的两个字符串。

【问题讨论】:

  • 订单是否重要,即您是否在寻找“hihello”?
  • 无顺序无所谓。

标签: javascript arrays string insert


【解决方案1】:

我创建了一个正则表达式,以便尽可能多地找到彼此相邻的单词。正则表达式是动态创建的,因此您可以传递您想要的任何单词列表。生成的正则表达式如下所示:

/(?:hello|there|hi){2,}/g

然后该函数使用相同的单词列表在每个单词之间添加一个空格:

function delimWords(string, words, delimiter) {
  const regex = new RegExp(`(?:${words.join('|')}){2,}`, 'g');
  const endDelim = new RegExp(`\\${delimiter}$`);

  return string.replace(regex, (match) => {
    return words
      .reduce((a, word) => a.split(word).join(word + delimiter), match)
      .replace(endDelim, '');
  });
}


const words = ['hello', 'there', 'hi'];
const longString = 'This is a string hellotherehi therehi hihi hihello helloperson';

console.log(delimWords(longString, words, ' '));
console.log(delimWords('hellohello', words, '.'));
console.log(delimWords('hellothere', words, '.'));

【讨论】:

  • 我不太了解函数内部的代码(但希望哈哈)。但它似乎只适用于空间。当我使用另一个字符(例如点)时,它会在字符串的末尾附加一个点。但由于某种原因,只有当有两个不同的词时。所以“hellohello”变成了“hello.hello”,但是“hellothere”变成了“hello.there”。 codepen.io/NoobConfirmed/pen/VBMQZR
  • @Tim,我已经更新了处理该用例的答案(不同的分隔符)。您现在可以将所需的分隔符传递给函数:delimWords(string, words, delimiter)。如果您看到任何令人困惑的具体内容,请告诉我,我可以在这些区域对代码进行注释。
  • 谢谢!我对此有点陌生。我今天第一次学习正则表达式,我通常对 javascript 很烂。所以我不太了解它如何在两者之间插入一个字符或分隔符 RegExp 如何工作。还有你为什么要使用这些“`”?
  • @Tim,我写了整个函数的解释in this JSFiddle
【解决方案2】:

这行得通吗?

var arr =  ["hello", "there", "hi"];

for (var i = 0; i < arr.length -1; i++) {
  if (arr[i] + arr[i+1] === "hellothere") {
    arr.splice(i + 1, 0, "");
    break;
  }
}
console.log(arr);

【讨论】:

    【解决方案3】:

    你可以找到后面两个单词的索引并插入一个想要的字符。

    var words = ["hello", "there", "hi"],
        string = "randomtext hellothere more random text";
    
    words.some((s, i, a) => {
        var pos = string.indexOf(s + a[i + 1]);
        if (pos !== -1) {
            string = string.slice(0, pos + s.length) + '^' + string.slice(pos + s.length);
            return true;
        }
    });
    
    console.log(string);

    【讨论】:

    • 这仅适用于字符串“hellothere”,但我需要它与“hellohi”、“hellohello”和“randomtext hellothere”一起使用。
    猜你喜欢
    • 1970-01-01
    • 2021-12-14
    • 2018-08-27
    • 2018-05-30
    • 2020-11-28
    • 2011-02-24
    • 2014-03-03
    • 2011-11-09
    • 2013-05-18
    相关资源
    最近更新 更多