javascript - applying regular expression for text highlight -
i using jqxdataadapter jqxwidgets in code 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 (var = 0; < length; i++) { console.log("checking words here: " +records[i].word_text);// displays 5 words in console log 1 } html = "<div style='margin: 10px;'><pre>" + records[1].note_content + "</pre></div>"; //records[1].note_content shows long paragraph of text words highlight // correct way apply regular expression? (var = 0; < 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 noticing here?: " + html); $("#doccontent").html(html); }, loaderror: function (xhr, status, error) { }, beforeloadcomplete: function (records) { } });
i wondering, regular expression applied correctly because, every in document, noticing words needs highlighted surrounded 2 <span>
tags. example, <span style="background-color:#f3f315;"><span style="background-color:#f3f315;">car</span></span>
here jsfiddle give idea what's going on doesn't have above code in it. words getting highlighted don't understand reason behind 2 span tags getting added.
you have both lowercase , uppercase words in test array:
var data = [{ name: 'car' }, { name: 'car' }, { name: 'bus' }, { name: 'bus' }, {
and regex case insensitive, i
in list of flags use:
new regexp(records[i].word_text, 'ig')
this means loop match car
against car
(case insensitive), wrap in span, match car
against car
(again case insensitive) , wrap in second span.
you either want match specific case of words in test array removing i
flag , keep g
(global):
new regexp(records[i].word_text, 'g')
or want remove duplicate case entries array , keep i
flag, words aren't matched more once.
Comments
Post a Comment