for a more general way to replace your *
in words to match:
NOTE: the code should watch fore more specific regex characters or it could break, for example words with round brackets in it would capture groups, etc. Generally they can be escaped with a \
(just the same way i escaped *
in the regex /\*/
). In a string you need to double the \
, like in '\\S*'
EDIT: added the regex (?:\\s|^)
at beginning and (?:\\s|$)
at end of words, so that test*
doesn't highlight the last part of Adtest
but the whole word if it corresponds. (it verifies that there is a space or start/end of string around the word)
EDIT 2: following last comments and the fact that the regex couldn't highlight successive words: it was because the spaces were captured and thus transferred into the span, making it impossible to detect the space for following word. Updated with capturing spaces separately and re-inserting them before and after the span. Added i
flag for capitals too.
var row = {
"Abstract": "This reference is to serve test as a useful reference for testing whether the styling of reference works or not. Adtest all occurrences of 'reference' should be given a color of red tests"
};
//here i need a truncation for examaple test*
var wordsToHighlight = 'reference test*';
var result = row["Abstract"];
wordsToHighlight.split(" ").forEach(function (word) {
word = word.replace(/\*/g, '\\S*');
result = result.replace(new RegExp('(\\s|^)(' + word + ')(\\s|$)', "gi"),'$1<span style="color: red;">$2</span>$3');
});
document.querySelector("#result").innerHTML = result;
wordsToHighlight = 'This is reference *test*';
result = row["Abstract"];
wordsToHighlight.split(" ").forEach(function (word) {
word = word.replace(/\*/g, '\\S*');
result = result.replace(new RegExp('(\\s|^)(' + word + ')(\\s|$)', "gi"),'$1<span style="color: red;">$2</span>$3');
});
document.querySelector("#result2").innerHTML = result;
<div id="result"></div>
<br/>
<div id="result2"></div>