首页 > 解决方案 > JavaScript - 检查字符串是否包含数组中彼此相邻的两个字符串并在其间插入字符串

问题描述

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

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

标签: javascriptarraysstringinsert

解决方案


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

/(?: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, '.'));


推荐阅读