javascript - 将输入文本与字符串数组进行比较后,突出显示结果中的匹配词

标签 javascript jquery html css

我有一个用于输入输入文本的输入字段和一个按钮。我还有一组预定义的单词。 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/

相关文章:

javascript - 快速下载数据:image from chromes developer tools network window?

javascript - 有没有办法将 Javascript SpeechRecognition API 与音频文件一起使用?

jquery - 使用 JQuery live 获取 img id 值时出现问题

jquery - $(this).find ("li") 和 $ ("li", $(this)) 之间的区别

html - 将 ul 在 div 中垂直和水平居中

javascript - Window.open 作为模态弹出窗口?

javascript - 如何隐藏*单个* MVC/Kendo tabstrip 选项卡?

javascript - 当 float 部分为空时,从 JQuery 中的输入元素获取数值不起作用

javascript - Slider Revolution 响应式 jQuery Slider - 嵌入 YouTube 打破幻灯片自动前进

html - HTML5 主要元素的用途