0

I am trying to highlight search terms in display results. Generally it works OK based on code found here on SO. My issue with it is that it replaces the substring with the search term, i.e. in this example it will replace "LOVE" with "love" (unacceptable). So I was thinking I probably want to find the index of the start of the substring, do an INSERT of the opening <span> tag, and do similar at the end of the substring. As yafs may be quite long I'm also thinking I need to integrate stringbuilder into this. Is this do-able, or is there a better way? As always, thank you in advance for your suggestions.

string yafs = "Looking for LOVE in all the wrong places...";
string searchTerm = "love";

yafs = yafs.ReplaceInsensitive(searchTerm, "<span style='background-color: #FFFF00'>" 
+  searchTerm + "</span>");
Community
  • 1
  • 1
Darkloki
  • 676
  • 1
  • 13
  • 31

3 Answers3

1

how about this:

public static string ReplaceInsensitive(string yafs, string searchTerm) {
    return Regex.Replace(yafs, "(" + searchTerm + ")", "<span style='background-color: #FFFF00'>$1</span>", RegexOptions.IgnoreCase);
}

update:

public static string ReplaceInsensitive(string yafs, string searchTerm) {
    return Regex.Replace(yafs,
        "(" + Regex.Escape(searchTerm) + ")", 
        "<span style='background-color: #FFFF00'>$1</span>",
        RegexOptions.IgnoreCase);
}
y.aoki
  • 51
  • 1
  • 4
0

Does what you need:

static void Main(string[] args)
{
    string yafs = "Looking for LOVE in all the wrong love places...";
    string searchTerm = "LOVE";

    Console.Write(ReplaceInsensitive(yafs, searchTerm));
    Console.Read();
}

private static string ReplaceInsensitive(string yafs, string searchTerm)
{
    StringBuilder sb = new StringBuilder();
    foreach (string word in yafs.Split(' '))
   {
        string tempStr = word;
        if (word.ToUpper() == searchTerm.ToUpper())
        {
            tempStr = word.Insert(0, "<span style='background-color: #FFFF00'>");
            int len = tempStr.Length;
            tempStr = tempStr.Insert(len, "</span>");
        }

        sb.AppendFormat("{0} ", tempStr);
    }

    return sb.ToString();
}

Gives:

Looking for < span style='background-color: #FFFF00'>LOVE< /span> in all the wrong < span style='background-color: #FFFF00'>love< /span> places...

DGibbs
  • 14,316
  • 7
  • 44
  • 83
0

Check this code

    private static string ReplaceInsensitive(string text, string oldtext,string newtext)
    {
        int indexof = text.IndexOf(oldtext,0,StringComparison.InvariantCultureIgnoreCase);
        while (indexof != -1)
        {
            text = text.Remove(indexof, oldtext.Length);
            text = text.Insert(indexof, newtext);


            indexof = text.IndexOf(oldtext, indexof + newtext.Length ,StringComparison.InvariantCultureIgnoreCase);
        }

        return text;
    }
yazan
  • 600
  • 7
  • 12