JavaScript - 检查字符串是否包含数组中彼此相邻的两个字符串并在其间插入字符串

标签 javascript arrays string insert

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

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

最佳答案

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

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

关于JavaScript - 检查字符串是否包含数组中彼此相邻的两个字符串并在其间插入字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51521915/

相关文章:

c# - C#子字符串引发异常

python - 查找列表中每个字符串之间的最大差异

javascript - 如何使用免费 IdP(例如 samling)测试 saml2-js?

c# - 用户名的正则表达式?

javascript - 如何将两个更新请求合并为一个?

javascript - 从字符串中删除前导逗号

javascript - 观察 Polymer 上的 "ended"媒体事件

java - 将字符串数组的数组写入文件(txt、csv 等)

java - 您好,我如何找到数组中的值和位置

c - 为什么我会遇到段错误(strcmp 或 fgets)?