Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JavaScript-检查字符串是否包含数组中相邻的两个字符串,并在两个字符串之间插入字符串_Javascript_Arrays_String_Insert - Fatal编程技术网

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

JavaScript-检查字符串是否包含数组中相邻的两个字符串,并在两个字符串之间插入字符串,javascript,arrays,string,insert,Javascript,Arrays,String,Insert,我想检测数组中是否有两个相邻的字符串,然后在两个字符串之间插入另一个字符串。 因此,如果我的数组包含[“hello”,“there”,“hi”],并且我选中了这个字符串“hellothere”,那么它将在这两个字符串之间插入字符串“”,这样它将以“hello there”结尾。如果我有两个相同的单词相邻,这也应该适用 我的问题是,我不知道如何检查一个字符串是否包含一个数组中相邻的两个字符串。这样行吗 var arr = ["hello", "there", "hi"]; for (var i

我想检测数组中是否有两个相邻的字符串,然后在两个字符串之间插入另一个字符串。
因此,如果我的数组包含[“hello”,“there”,“hi”],并且我选中了这个字符串“hellothere”,那么它将在这两个字符串之间插入字符串“”,这样它将以“hello there”结尾。如果我有两个相同的单词相邻,这也应该适用

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

这样行吗

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);
var arr=[“你好”,“你好”,“你好”];
对于(变量i=0;i
您可以找到以下两个单词的索引并插入所需字符

var words=[“你好”,“你好”,“你好”],
string=“randomtext hellother更多随机文本”;
单词。一些((s,i,a)=>{
var pos=string.indexOf(s+a[i+1]);
如果(位置!=-1){
string=string.slice(0,pos+s.length)+'^'+string.slice(pos+s.length);
返回true;
}
});

console.log(字符串)我创建了一个正则表达式来查找尽可能多的相邻单词。正则表达式是动态创建的,因此您可以传递所需的任何单词列表。生成的正则表达式如下所示:

/(?:hello|there|hi){2,}/g
然后,该函数使用相同的单词列表在这些单词之间添加一个空格:

函数delimWords(字符串、单词、分隔符){
const regex=new RegExp(`(?:${words.join('|')}){2,}`,'g');
const endDelim=new RegExp(`\\\${delimiter}$`);
返回字符串.replace(正则表达式,(匹配)=>{
回话
.reduce((a,单词)=>a.split(单词).join(单词+分隔符),match)
.替换(endDelim,);
});
}
const words=['hello','there','hi'];
const longString='这是一个字符串hellotherhi therehi hi hi hi hi hello helloperson';
log(delimWords(longString,words,);
日志(delimWords('hellohello',words');

日志(delimWords('hellother',words,')顺序重要吗,例如,您是否在寻找“hihello”?没有顺序不重要。这只适用于字符串“hellothere”,但我需要它来处理“hellohi”、“hellohello”和“randomtext hellothere”。我不太理解函数内部的代码(希望哈哈)。但它似乎只适用于空格。当我使用另一个字符(如点)时,它会在字符串末尾附加一个点。但由于某些原因,只有在有两个不同的单词时才会添加。因此,“hellohello”更改为“hello.hello”,但“Helloother”更改为“hello.there”。@Tim,我已更新了答案以处理该用例(不同的分隔符)。现在可以将所需的分隔符传递给函数:
delimWords(字符串、单词、分隔符)
。如果您看到任何令人困惑的特定内容,请告诉我,我可以在这些区域对代码进行注释。谢谢!我对这方面有点陌生。我今天第一次学习正则表达式,我对javascript的了解一般都很差。所以我不太了解它是如何在两者之间插入字符的,或者delimeter RegExp是如何工作的。为什么你在用这些“`”吗?蒂姆,我写了一篇关于整个函数的解释