I need some help with my code. What i am trying to do is find one string at a time in a sentence and replace the same string with a span tag.
I have achieved same with javascript but I am unsure of how to do it in C#
Code in js:
//this function takes 'buffer' as content &
//search query (multiple string values) as replaceStrings and highlights the query
function highlitor(buffer, replaceStrings)
{
var highlightedText = buffer;
for (var i = 0; i < replaceStrings.length; i++)
{
var exp = new RegExp("(" + replaceStrings[i] + ")", "gi");
highlightedText = highlightedText.replace(exp, "<span class='highlight-search-text'>$1</span>");
}
return highlightedText;
}
For example
buffer=" This is an exciting and enhansive test" replaceStrings=[exciting,enhace];
highlightedText="This is an <span class='highlight-text'>exciting</span> and <span class='highlight-text'>enhansive</span> test"
Thanks in advance.
I think you just need
String.Replace
in a loop:You don't need
Distinct
if the list doesn't contain duplicates.UPDATE: as it seems things are much more complicated. You want to replace parts by preserving the original case when the pattern is part of the final replacement string.
Here is a modified version of my above method that uses an extended version of
String.Replace
:Here is the method that replaces strings case-insensitively and supports keeping the original case:
It's algorithm based on: Fastest C# Case Insenstive String Replace.