VSri58
VSri58

Reputation: 3761

Highlight the matching words in the result after comparing the input text with a string array

I have an input field to enter the input text and a button. I also have an array of predefined words. JSFiddle

var strArray = ["critical","normal","high","low","blood pressure","fracture"];

Assume the input text is

"the patient is in critical condition and the blood pressure is very low"

Clicking on the Submit button should compare the input text with all the string in the array and find out the matching words and display the same text as output with the matched words highlighted in a certain color.

Expected Output

The same text with the matched words highlighted.

"the patient is in critical condition and the blood pressure is very low"

Is there anyway to achieve this using javascript / jQuery ?

Upvotes: 1

Views: 1638

Answers (2)

YaswanthJg
YaswanthJg

Reputation: 129

You can use below code..

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);
});

Updated Fiddle..

https://jsfiddle.net/yeswanth/nye9skd7/

Upvotes: 0

dandavis
dandavis

Reputation: 16726

Using a dynamic Regexp to ignore case and hit only full-word matches and [].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>"

Upvotes: 6

Related Questions