I am implementing a website search and am trying to highlight the words the user searched for using the below code:
data = Regex.Replace(data, Model.SearchCriteria, "<strong>" + Model.SearchCriteria + "</strong>", RegexOptions.IgnoreCase);
However if data is “I went North towards Canada” and the user has searched for “north” the results will show “I went north towards Canada” with north highlighted however the actual data has been replaced incorrectly slightly.
How can I keep the returned data in tact whilst higlighting what the user searched for?
In this case you need to use a substitution pattern to put the original text into the replaced string vs. the explicit search criteria
Putting parens around the search criteria places it into an unnamed group. You can then reference this group by index in the replacement string by using
$1. This will then use the original matched text.Info on substitution strings in Regex.Replace