Highlight keyword in string


/ Published in: C#
Save to your folder(s)



Copy this code and paste it in your HTML
  1. public string HighlightKeywords(string input, string keywords)
  2. {
  3. if (input == string.Empty || keywords == string.Empty)
  4. {
  5. return input;
  6. }
  7.  
  8. var keywordChar = keywords.Split(' ');
  9. foreach (var keyword in keywordChar)
  10. {
  11. try
  12. {
  13. input = Regex.Replace(input, keyword, string.Format("<span class=\"highlight\">{0}</span>", "$0"), RegexOptions.IgnoreCase);
  14. }
  15. catch (Exception)
  16. {
  17. // Log the error.
  18. }
  19. }
  20.  
  21. return input;
  22. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.