Monday, 13 February 2012

ASP: convert a string into a link


If you often visit social networks or, generally speaking, discussion web sites, you surely have noticed that sometimes when you insert a message or a post, every possible link is automatically recognised and "transformed" into a clickable link. How is it done?

With ASP we can manipulate a given string, find a possible link and change it.

The code
The code is quite simple:
Dim str
str= "This is a link"

Dim strS
strS = Split(str, " ")

Dim strLink, i
i = 0
For i = 0 To Ubound(strS)
If InStr(strS(i), "http://") Then
strLink= "<a href='" & strS(i) + "'>" + strS(i) & "</a>"
strLink = strS(i)
End If
Response.Write strLink & " "
Ok, let me explain it to you.
str is our string. It can be submitted by a form, retrieved from a database or else.

We first split the string (str) into an array (using the space as separator).
We then use a for cycle to go through the array and check if "http://" is present. If so we convert it into a link. After that we show the complete text. We can obviously use strLink the way we prefer.

Easy and simple.

0 thoughts:

Post a Comment

Comments are moderated. I apologize if I don't publish comments immediately.

However, I do answer to all the comments.