I need to write some code that performs an HTML highlight on specific keywords in a string.
If I have comma separated list of strings and I would like to do a search and replace on another string for each entry in the list. What is the most efficient way of doing it?
I'm currently doing it with a split, then a foreach and a Regex.Match. For example:
string wordsToCheck = "this", "the", "and";
String listArray[] = wordsToCheck.Split(',');
string contentToReplace = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.";
foreach (string word in listArray)
{
if (Regex.Match(contentToReplace, word + "\\s+", RegexOptions.IgnoreCase).Success)
{
return Regex.Replace(contentToReplace , word + "\\s+", String.Format("<span style=\"background-color:yellow;\">{0}</span> ", word), RegexOptions.IgnoreCase);
}
}
I'm not sure this is the most efficient way because the list of words to check for could get long and the code above could be part of a loop to search and replace a bunch of content.