Sakshi Sakshi - 7 months ago 19
HTML Question

Javascript word highlighting in a text

I have a variable called output in Javascript, which has the following content.

var output = "Comparison : CT head dated 11/01/2009. Correlation is made with the Outside MRI brain dated 11/03/2014 and noncontrast MRI brain dated 06/12/2011.\n\nImpression : Extensive nodular soft tissue Neoplasm, as detailed above, with mass effect on the right lateral ventricle, resulting in a trapped temporal horn, with moderate to severe distention. Low attenuation surrounding the right temporal horn may represent transependymal flow of CSF. A contrast-enhanced MRI of the brain is recommended to further delineate the extent of disease. Nonspecific hypodense subdural collection along the convexity of the right frontal lobe, without much mass-effect, measuring 6 mm in thickness, may represent chronic subdural blood. Biparietal approach VP shunt catheters with the tips in the lateral ventricles."


I want to search and highlight the words "mass effect" and "neoplasm" in them when I display the content of output. The above content is dynamic. Assuming I have a variable output which has the text and an array called arr1 which has the elements to be searched and highlighted, how can I display the entire content with words highlighted in javascript?Please let me know. Thanks in advance.

Answer

Assuming you want literal phrases that are generally just words (no special characters or punctuation), you could use a regular expression similar to this (I've also added case insensitivity):

var output = "Comparison : CT head dated 11/01/2009. Correlation is made with the Outside MRI brain dated 11/03/2014 and noncontrast MRI brain dated 06/12/2011.\n\nImpression : Extensive nodular soft tissue Neoplasm, as detailed above, with mass effect on the right lateral ventricle, resulting in a trapped temporal horn, with moderate to severe distention. Low attenuation surrounding the right temporal horn may represent transependymal flow of CSF. A contrast-enhanced MRI of the brain is recommended to further delineate the extent of disease. Nonspecific hypodense subdural collection along the convexity of the right frontal lobe, without much mass-effect, measuring 6 mm in thickness, may represent chronic subdural blood. Biparietal approach VP shunt catheters with the tips in the lateral ventricles.";
var arr1 = ['mass effect', 'neoplasm'];
var regex = new RegExp('('+arr1.join('|')+')', 'gi');
output = output.replace(regex, "<b>$1</b>");

// the following line is for debug purposes only. I've added it
// to better display what's happening just for the Stackoverflow
// code snippet editor.
document.body.innerHTML = output.replace(regex, "<b>$1</b>");
b {
  background: yellow;
  font-weight: normal;
}

Comments