0

I inherited a function written by another developer which I'm finding impossible to debug.

function getHighlightWordsForIssueHTML(cIssue, nIssueNum, arWordsToHighlight, strStartingHTML, strReplacementHTML)
{
var nIssueStartIndex = strStartingHTML.indexOf("<issuestart" + nIssueNum + "_");
var nIssueEndIndex = strStartingHTML.indexOf("<issueend" + nIssueNum + "_");
var strRelevantPart = strStartingHTML.slice(nIssueStartIndex, nIssueEndIndex);
for (var i = 0; i < arWordsToHighlight.length; i++)
{
    var strWord = arWordsToHighlight[i];
    strRelevantPart = strRelevantPart.replace(new RegExp(strWord, 'g'),
        String.format(strReplacementHTML, strWord));
}

strStartingHTML = strStartingHTML.replaceBetween(nIssueStartIndex,
        nIssueEndIndex, strRelevantPart);
return strStartingHTML;
}

This is returning an error for strRelevantPart = strRelevantPart.replace(new RegExp(strWord, 'g'), when the text it is looking for (as caught by the strWord variable) contains a parentheses. As in this example:

"12) months after the"

The error in question is:

Uncaught SyntaxError: Invalid regular expression: /12) months after the/: Unmatched ')'

Can you guys help me fix this?

  • Why are you using regular expressions to do a replacement when there's no expression? Just use the normal string replacement method. – Phylogenesis Nov 03 '16 at 09:51
  • 1
    In other words, just use `strRelevantPart.replace(strWord, String.format(strReplacementHTML, strWord));` – Phylogenesis Nov 03 '16 at 09:56
  • Ok. Just to be clear, I didn't write the function. I'm tasked (vexingly) with fixing it. I'm gonna try your fix, @Phylogenesis – JoshWeinstein Nov 03 '16 at 09:58

0 Answers0