如何在JavaScript中从字符串中删除除某些子字符串(以列表形式给出)之外的所有字符



在JavaScript中,假设我们有一个字符串:"敏捷的棕色狐狸跳过懒狗;

然后我们有一个子字符串列表,比如:["狗"、"棕色"、"The"、"jumps"]

如何过滤字符串中的其他字符,但不过滤列表中给定的子字符串?

因此,在这种情况下的结果应该是:;"棕色跳跃";

我想到的第一个解决方案是在每次迭代中使用循环和RegExp,即:

const listOfSubstrings = ["dog", "brown", "The", "jumps"];
let theString = "The quick brown fox jumps over the lazy dog";
for (const substring of listOfSubstrings) {
theString = theString.replace(new RegExp(`[^${substring}]`, "g"), "");
}

然而,如果我们仔细查看(或测试)代码,我们就会看到并理解循环后什么都没有了:在每次迭代中,除了列表中的当前元素之外,其他所有元素都会被删除。准确地说,在第二次迭代之后什么都没有留下。

那么,在给定字符串和子字符串列表的情况下,我提供的最终结果是如何实现的,有什么想法吗?

您可以匹配这些子字符串,并连接所有匹配项。

const result = theString.match(/(?:dog|brown|The|jumps)/g).join("");

请参阅regex101中的模式演示和下面提供的堆栈片段。

const theString = "The quick brown fox jumps over the lazy dog";
const listOfSubstrings = ["dog", "brown", "The", "jumps"];
// generate regex pattern from listOfSubstrings
const regex = new RegExp('(?:' + listOfSubstrings.join("|") + ')','g');
// extract and join matches
const result = theString.match(regex);
if(result) {
console.log(result.join(""));
} else {
console.log('No matches!');
}

你可以试试这个:

const listOfSubstrings = ["dog", "brown", "The", "jumps"];
let theString = "The quick brown fox jumps over the lazy dog";
let result = "";
const theStringArray = theString.split(" ");
theStringArray.forEach(s => {
if(listOfSubstrings.includes(s)){
result += s;
}
})

但如果您的listOfSubstrings较大,则速度可能会较慢。为此,您可以将listOfSubstrings转换为字典

const listOfSubstrings = ["dog", "brown", "The", "jumps"];
let theString = "The quick brown fox jumps over the lazy dog";
let result = "";
const theStringArray = theString.split(" ");
let substrings = {};
// converting array to dictionary
listOfSubstrings.forEach(e=>{
substrings[e] = e;
})
theStringArray.forEach(s => {
if(substrings[s] !== undefined){
result += s;
}
})

使用dictionary的原因是,检查键是否存在在O(1)中有效,而array.includes在O(n)中有效。

此解决方案按空格分割输入,按感兴趣的单词过滤列表,并将其连接回一个没有空格的字符串以获得所需结果:

const input = 'The quick brown fox jumps over the lazy dog';
const listOfSubstrings = ["dog", "brown", "The", "jumps"];
let regex = new RegExp('^(' + listOfSubstrings.join('|') + ')$');
let result = input.split(' ').filter(str => regex.test(str)).join('');
console.log(result);

输出:

Thebrownjumpsdog

最新更新