如何在单词数组中找到句子并连接单词



按照这个例子:

const arrayOfSentences = ['fallen little short', 'hold the nominal office of governess', 'shadow of authority', 'the real evils indeed']
const arrayOfwords = ['who', 'had','fallen', 'little','short','of','a','mother','in','affection','hold','the','nominal','office','of','governess','the','mildness','of','her','temper','had','hardly','allowed','her','to','impose','any','restraint;','and','the','shadow','of','authority','being','now','long','passed','away,','they','had']

输出应该是单词数组,但句子合并,例如("fallen","little","short"->"fallen little short"(:

const mergedArray = ['who', 'had','fallen little short','of','a','mother','in','affection','hold the nominal office of 
governess','the','mildness','of','her','temper','had','hardly','allowed','her','to','impose','any','restraint;','and','the','shadow of authority','being','now','long','passed','away,','they','had']

这里有一个偷偷摸

摸的方法:

const arrayOfSentences = ['fallen little short', 'hold the nominal office of governess', 'shadow of authority', 'the real evils indeed']
const arrayOfwords = ['who', 'had','fallen', 'little','short','of','a','mother','in','affection','hold','the','nominal','office','of','governess','the','mildness','of','her','temper','had','hardly','allowed','her','to','impose','any','restraint;','and','the','shadow','of','authority','being','now','long','passed','away,','they','had']
let sentence = arrayOfwords.join(' ');
arrayOfSentences.forEach(s => {
sentence = sentence.replace(s, s.replace(/s/g, '|'));
});
const mergedArray = sentence.split(' ').map(s => s.replace(/|/g, ' '));
console.log(mergedArray);

基本上,它所做的是使整个arrayOfwords成为一个句子。

然后遍历arrayOfSentences以查找该句子中的外观,并将其替换为一些占位符。

然后将句子重新拆分为数组,并将占位符替换为arrayOfSentences中的内容。

最新更新