2

I need to parse a sentence. If I find a hash in the sentence, I would like to bold it.

Example : Bonjour #hello Hi => Bonjour #hello Hi

1
  • 5
    Probably belongs on StackOverflow, and post what code you've tried along with the question. Commented Apr 15, 2011 at 23:27

2 Answers 2

6

Seems like a good situation for regex

I'd do something like this

boldHashes("Bonjour #hello Hi");

...

private string boldHashes(string str)
{
    return Regex.Replace(str, @"(#\w+)", "<strong>$1</strong>");
}

In this case we're matching a literal hash # plus a word of any length \w+ and group it between () so we can use the $1 substitions in the Regex.Replace function


Updated jQuery doing the same thing.

Something like:

HTML

<div id="myDiv">Bonjour #Hello hi</div>

jQuery

$('#myDiv').html($('#myDiv').text().replace(/(#\w+)/g, '<strong>$1</strong>'));
Sign up to request clarification or add additional context in comments.

2 Comments

Is it possible to use it in the view ? Because I need it in the html. Because I want to save this string without <strong></strong>
How to do the same thing with jQuery ? please ?
1

There's probably a more elegant way to do this but you can use the String.IndexOf method to find the first instance of the hash like so

String myString = "Bonjour #hello hi";
int index = myString.IndexOf('#');
if(index>-1) //IndexOf returns -1 if the character isn't found
{
  //search for the next space after the hash
  int endIndex=mystring.IndexOf(' ',index+1)
  myString=MakeBold(myString,index,endIndex);
}

All that's left for you is to implement the MakeBold function.

1 Comment

also, you probably want to extend the function to take into account multiple hashes in the string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.