gpt4 book ai didi

javascript - 如何匹配原始字符串中的字符串?

转载 作者:行者123 更新时间:2023-11-30 08:18:46 25 4
gpt4 key购买 nike

我想从一个原始字符串中匹配一个字符串
例如:
假设原始字符串是
“敏捷的棕色狐狸跳过一只懒狗。”
另一个字符串是
“快过狗”
因此,如果上述字符串中的单词出现在原始字符串中,那么它应该返回 true。我该怎么做?

我使用了方法indexOf(filter) > -1
只有当我给出像
这样的连续字符串时它才有效“棕狐”
但如果我将 "BROWN JUMPS" 作为字符串,则它不起作用。

var string_1 = "QUICK BROWN";
var string_2 = "QUICK FOX";
// this returns true
if (original.toUpperCase().indexOf(string_1) > -1) {
console.log("true");
} else {
console.log("false");
}

// this returns false
if (original.toUpperCase().indexOf(string_2) > -1) {
console.log("true");
} else {
console.log("false");
}

那么如何匹配原始字符串中的字符串呢?

最佳答案

我将匹配两个字符串中的所有单词字符,以获得一个单词数组,并将原始字符串的单词(要搜索的单词)放入一个集合中。然后检查 .every 中是否存在其他单词之一:

const orig = "THE QUICK BROWN FOX JUMPS OVER A LAZY DOG.";
// if the strings may not have any words in them at all,
// then alternate with the empty array, since the match will be null:
const origWordsSet = new Set(orig.match(/\w+/g) || []);
const verify = str => (str.match(/\w+/g) || []).every(word => origWordsSet.has(word));

console.log(
verify("QUICK OVER A DOG"),
verify("QUICK BROWN"),
verify("QUICK FOX"),
verify("FOO")
);

关于javascript - 如何匹配原始字符串中的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57440068/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com