我有一个输入字段用于输入输入文本和一个按钮。我还有一系列预定义的单词。 JSFiddle
var strArray = ["critical","normal","high","low","blood pressure","fracture"];
假设输入文字为
“患者情况危急,血压非常高 低“
单击“提交”按钮,应将输入文本与数组中的所有字符串进行比较,找出匹配的单词,并显示与输出相同的文本,并以特定颜色突出显示匹配的单词。
预期输出
突出显示匹配单词的相同文字。
“患者处于严重状态且血压非常 的低“
无论如何使用javascript / jQuery来实现这个目标吗?
答案 0 :(得分:6)
使用动态正则表达式忽略大小写并且仅匹配全字匹配和[] .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>"
答案 1 :(得分:0)
您可以使用以下代码..
var strArray = ["critical", "normal", "high", "low", "blood pressure", "fracture"];
$("input[type='submit']").on('click', function (es) {
var tmp = [];
var stmt = $("input[type='text']").val();
var stmt_arry = stmt.split(" ");
$.each(strArray, function (i, vals) {
$.each(stmt_arry, function (j, sVal) {
if (sVal == vals) {
stmt_arry[j] = "<b>" + sVal + "</b>";
}
});
});
var req_stmt = stmt_arry.join(" ");
$("#result").html(req_stmt);
});
更新了小提琴..