Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

we have a rich text field in one of our objects that contains an html-document. I have created a search page and a user can click on a 'preview'-button which opens the html in a lightbox. I want to highlight the search terms, but I want to do it case sensitive. So far I came up with this ('a' contains the html and is a string):

string replaceToken = '(?i)'+highlightTerm;
a = a.replaceAll(replaceToken,'<span class="highlight">'+highlightTerm+'</span>');

This does replace all occurrences regardless of the case. However it replaces them with whatever the user searched for. So if a user searched for 'DoOr' it will highlight 'door' as 'DoOr'. But I want to highlight the original word without changing it. Any thoughts on that?

share|improve this question
Marcel - You can take your answer out of your question and post it as answer. Then you can accept it later if you want. It's OK to Ask and Answer Your Own Questions. – Peter Knolle Jan 23 '13 at 11:40
up vote 0 down vote accepted

Here's a rough pass at a solution. (Care of the original requestor who posted the answer in the question)

boolean all_occurences_processed = false;
integer pos1 = 0;
integer pos2 = 0;
string v1,v2,v3;
integer newpos = 0;

for (String hlt:Highlightsterms) {
  all_occurences_processed = false;
  while (!all_occurences_processed) {
    if ((pos1!=-1) && (pos1>newpos)) {
      v1 = a.substring(0, pos1);
      v2 = a.substring(pos1, pos2);
      v3 = a.substring(pos2);
      a = v1+'<span class="hl">'+v2+'</span>'+v3;
      newpos = pos2+24;
    } else {
      all_occurences_processed = true;
share|improve this answer

Use Pattern and Matcher classes. The Apex documentation actually just links to the java doc:

 * @description Wraps matched terms in a string with a span.
 * @param       String toHighlight   - the input markup to highlight with spans
 * @param       String highlightTerm - the regex to match against toHighlight
 * @return      String - the highlighted version of toHighlight
public static String highlightTerms(String toHighlight, String highlightTerm) {
    Matcher match = Pattern.compile('(?i)(' + highlightTerm + ')').matcher(toHighlight);
    String matched;
    String highlight;

    while(match.find()) {
        matched     =;
        highlight   = '<span class="highlight">' + matched + '</span>';
        toHighlight = toHighlight.replace(matched, highlight);

    return toHighlight;
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.