gpt4 book ai didi

javascript - 在字典 Javascript 中查找多个关键字

转载 作者:行者123 更新时间:2023-11-30 13:26:04 27 4
gpt4 key购买 nike

我正在尝试对某些内容执行字典查找,到目前为止我的方法只能查找单个单词,因为我使用的是 split(' ') 方法,仅在空格上进行拆分。我刚刚遇到了一些障碍,想知道你们是否有任何可靠的意见。就像如果我的字典中有两个单词的键会怎样。如下图

var  dictionary = { "Darth Vader" : "Bad Ass Father", "Luke": "Son of the Bad Ass",
"Skywalker" : "Last name of some Jedi Knights", "Luke SkyWalker" : "Son of the Bad Ass"}

这是我到目前为止得到的代码,它显然适用于单个单词,但不适用于多个关键字。 getElementsByClassName 是一个函数,用于返回找到的所有类的数组。

var body = '<div class="activity-inner"> This is a test glossary body paragraph to test glossary highlight of the Star Wars vocabulary. like Luke Skywalker and Darth Vader, Luke and Skywalker. </div> <div class="activity-inner">Hello glossary again here Luke Skywalker Darth Vader</div>';
document.write( body);
var matches = getElementsByClassName("activity-inner");
for (int i = 0; i < matches.length; i++;) {
var content = matches[i].innerHTML;
document.write(content);
var words = content.split(' ');



for (var j = 0; j < words.length; j++) {
var temp = words[j].replace(/[^\w\s]|_/g, "")
.replace(/\s+/g, " ").toLowerCase();
if (temp in dictionary) {
words[j] = "<span class='highlight' style='color:green;'>"+words[j]+"</span>";
}
document.write(words[j] +"<br />");



}
body = words.join(' ');
document.write( "<br /> <br />" + body);
}

上面的例子是行不通的。然而,我字典里的一些东西会是这样的。我应该如何处理这个问题,并尽可能避免这种情况?谢谢!

最佳答案

构造一个正则表达式,由字典的所有键组成(以防止替换被再次替换)。然后,使用 String.replace(pattern, replace_function) 如下所示。

演示:http://jsfiddle.net/Z7DqF/

// Example
var dictionary = { "Darth Vader" : "Bad Ass Father", "Luke": "Son of the Bad Ass",
"Skywalker" : "Last name of some Jedi Knights", "Luke SkyWalker" : "Son of the Bad Ass"}
content = "....";

var pattern = [],
key;
for (key in dictionary) {
// Sanitize the key, and push it in the list
pattern.push(key.replace(/([[^$.|?*+(){}])/g, '\\$1'));
}
pattern = "(?:" + pattern.join(")|(?:") + ")"; //Create pattern
pattern = new RegExp(pattern, "g");

// Walk through the string, and replace every occurrence of the matched tokens
content = content.replace(pattern, function(full_match){
return dictionary[full_match];
});

关于javascript - 在字典 Javascript 中查找多个关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8413651/

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