Naveh Naveh - 2 months ago 8
Javascript Question

How to make the chosen substring as a link and bold?

<%
int amountOfTags = 0;
string text = "hi @dude im @cool kay";
int number1 = 1;
int number2 = 0;
for (int a = 0; a < text.Length; a++)
{
if (text.Substring(a, 1) == "@")
{
amountOfTags++;
}
}
for (int i = 0; i < text.Length; i++)
{
if (text.Substring(i, 1) == "@")
{
number1 = i;
}
if (text.Substring(i, 1) == " " && number1 > number2)
{
number2 = i;
}
int number3 = number2 - number1;
if (number2 - number1 < 13 && number1 > 0 && number2 > 0 && number2 > number1 && number2 == i && amountOfTags != -1)
{
if (text.Substring(number1 + 1, number3) != ", ")
{
Response.Write(text.Substring(number1 + 1, number3 - 1));
amountOfTags--;
}
}
}
%>


Ok so this code takes a text for example "hi @dude im @cool kay" in ASP.NET and returns the text after the @, so the code will return me 'dude' and 'cool'
Now my question is, how to make the text it returns me from the substring to become a link and bold? (Like adding to that specific text an element).

Is it possible with ASP.NET or JS?

Answer

I would use a Regular Expression instead of all of that confusing substring logic. You could reduce the logic to a single line and include your desired anchor wrapper:

<% string text = "hi @dude im @cool kay"; %>
<%= Regex.Replace(text, @"@([\S]+)", @"<a href=""#""><b>$1</b></a>") %>

Note: I have included <b> tags for simplicity, but I would recommend removing them and using CSS to make the link bold.