我有一个用于输入输入文本的输入字段和一个按钮。我还有一组预定义的单词。 JSFiddle
var strArray = ["critical","normal","high","low","blood pressure","fracture"];
假设输入文本是
"the patient is in critical condition and the blood pressure is very low"
单击“提交”按钮会将输入文本与数组中的所有字符串进行比较,找出匹配的单词并显示与输出相同的文本,并以特定颜色突出显示匹配的单词。
预期输出
突出显示匹配词的相同文本。
"the patient is in critical condition and the blood pressure is very low"
有没有办法使用 javascript/jQuery 实现这一点?
最佳答案
使用动态正则表达式忽略大小写并只命中全字匹配和 [].forEach:
var r=["critical","normal","high","low","blood pressure","fracture"],
s="the patient is in critical condition and the blood pressure is very low";
// replace each keyword in r with a mark'd replacement:
r.forEach(function(a){
s=s.split(RegExp("\\b"+a+"\\b","i")).join("<mark>"+a+"</mark>");
});
// view s after replacements:
s; // == "the patient is in <mark>critical</mark> condition and the <mark>blood pressure</mark> is very <mark>low</mark>"
关于javascript - 将输入文本与字符串数组进行比较后,突出显示结果中的匹配词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26772661/