John John - 11 months ago 66
Javascript Question

applying regular expression for text highlight

I am using jqxDataAdapter for jqxWidgets in my code as follows:

var dataAdapter = new $.jqx.dataAdapter(source, {

loadComplete: function (records) {
var html;
var color = '#F3F315';

//Get data
var records = dataAdapter.records;
var length = records.length;
console.log("Checking Length: "+length);// Outputs 5
for (var i = 0; i < length; i++) {
console.log("checking Words here: " +records[i].word_text);// Displays five words in the console log one

html = "<div style='margin: 10px;'><pre>" + records[1].note_content + "</pre></div>"; //records[1].note_content shows a long paragraph of text with words to highlight

// Is this correct way to apply regular expression?
for (var i = 0; i < length; i++) {

html = html.replace(new RegExp(records[i].word_text, 'ig'), '<span style="background-color:' + color + ';">' + records[i].word_text + '</span>');

console.log("How many span tags you are noticing here?: " + html);
loadError: function (xhr, status, error) { },
beforeLoadComplete: function (records) {


I am wondering, is the regular expression applied correctly because, every where in the document, I am noticing the words that needs to be highlighted are surrounded by two
tags. For example,
<span style="background-color:#F3F315;"><span style="background-color:#F3F315;">CAR</span></span>

Here is the JSFiddle which will give you some idea what's going on but it doesn't have the above code in it. Words are getting highlighted but I don't understand the reason behind two span tags getting added.

Answer Source

You have both lowercase and uppercase words in your test array:

var data = [{
    name: 'CAR'
}, {
    name: 'Car'
}, {
    name: 'Bus'
}, {
    name: 'BUS'
}, {

And your regex is case insensitive, which is what the i is in the list of flags you use:

new RegExp(records[i].word_text, 'ig')

This means the loop will match CAR against car (case insensitive), wrap it in a span, then match Car against car (again case insensitive) and wrap it in a second span.

You either want to match the specific case of the words in the test array by removing the i flag and keep the g (global):

new RegExp(records[i].word_text, 'g')

Or you want to remove the duplicate case entries from your array and keep the i flag, so words aren't matched more than once.