Imran Rizvi
Imran Rizvi

Reputation: 7438

Wrap a word in string with '<b>' to make it Bold without changing word's original case

I have a string and I need to make a specific word Bold by surrounding it with <b>, so that when it will be rendered the text must be bold.

e.g. String word = "a1c"
String myString = "The allergy type a1c should be written A1C."

I can do the following:

String1.Replace(word,"<b>"+word+"<b>") 

but it will change all the A1c word to "a1c" irrespective of the original word's case.

"The allergy type <b>a1c<b> should be written <b>A1C<b>."

How can I do it without changing case, so that i can get output as

I know we can do it with a loop and index, but I wanted to know the best way that make use of advanced terms like RegEx or Linq or any small inbuilt machanism.

Upvotes: 3

Views: 55768

Answers (3)

Neeraj Kumar Gupta
Neeraj Kumar Gupta

Reputation: 2363

Check this code this is exactly I think you are looking for

string strRegex = @"<b>(?<X>.*?)</b>";
RegexOptions myRegexOptions = RegexOptions.IgnoreCase | RegexOptions.Multiline;
Regex myRegex = new Regex(strRegex, myRegexOptions);
string strTargetString = "Hellow world is my <b>first</b> application in <b>computer</b> world.";
        string NewString = strTargetString;
        foreach (Match myMatch in myRegex.Matches(strTargetString))
        {
            if (myMatch.Success)
            {
                NewString = NewString.Replace(myMatch.ToString(), myMatch.ToString().ToUpper());
            }
        }

Output in NewString

Hellow world is my FIRST application in COMPUTER world

Upvotes: 0

Rawling
Rawling

Reputation: 50104

You can do this with a single Regex.Replace call as follows:

var result = Regex.Replace(
    "The allergy type a1c should be written A1C.", // input
    @"a1c",                                        // word to match
    @"<b>$0</b>",                                  // "wrap match in bold tags"
    RegexOptions.IgnoreCase);                      // ignore case when matching

Upvotes: 9

MikeSmithDev
MikeSmithDev

Reputation: 15797

You can use a Regex to match the word, regardless of case:

string word = "a1c";
string myString = "The allergy type a1c should be written A1C.";
var regex = new Regex(word, RegexOptions.IgnoreCase);
foreach (Match m in regex.Matches(myString))
{
    myString = myString.Replace(m.ToString(), "<b>" + m.ToString() + "</b>");
}

PS. Consider a different route for bolding! Inline styling is not ideal.

Upvotes: 5

Related Questions