javascript - JavaScript - 检查字符串是否包含数组中彼此相邻的两个字符串并在其间插入字符串
问题描述
我想检测数组中每个字符串旁边是否有两个字符串,然后在其间插入另一个字符串。
因此,如果我的数组包含 ["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, '.'));
推荐阅读
- java - 在 Android 中更新安全提供程序
- excel - 将 Excel 语言从德语更改为英语
- php - 在php中使用时间戳获取所有时间
- maven - 如何通过 Maven 排除测试组?
- python - Tensorflow:使用 tf.Keras 层或 tf.Estimator API 时,何时需要运行 tf.Session()?
- c++ - 将较小的向量与较大的向量进行比较,以检查它是否在较小的末尾有所不同
- angular - Angular 6:从部分组件刷新路由
- json - Schema.org/Json - 关于定制、属性、医疗规格的付费专区问题
- python - pySpark 中的派生列,使用两列和前一行的值
- cors - 如何在 Vespa 中添加自定义过滤器包以启用 CORS?