Computing.Net > Forums > Web Development > Link Parser

Link Parser

Reply to Message Icon

Original Message
Name: WCWidgets
Date: June 28, 2008 at 17:14:59 Pacific
Subject: Link Parser
OS: Mac OS X v10.4.11
CPU/Ram: 500 MHz/512 MB RAM
Model/Manufacturer: Apple/iMac G3
Comment:

I am trying to build a JavaScript parser to create links from
an arbitrary string. Essentially, the function takes an
arbitrary string, splits it at 'http", and generates a link
from an array value, returning the rest of the text, or
returning plain text if no link is present. The code is
below:

function parseTextLinks(text) {
if (text.indexOf('http://') !=-1) {
var link_array = text.split("http://");
return link_array[0] + '<a onclick=\"window.open(\''
+ 'http://' + link_array[1] + '\')\">' + 'http://' +
link_array[1] + '';
}else{
return text;
}
}

This works very well, except that it adds all text that
follows the link. For example, if I embed the link at the
end of a sentence, it will embed the period. More
problematic, however, is when the link is placed at the
beginning or middle of the text, which results in the
portion before the link appearing normal, and then the
rest of the text becoming a link (which, obviously,
generates a garbage URL-example: If my sentence is,
"Look at http://www.google.com for an example", the link
becomes
"http://www.google.com%20for%20an%20example"-not
what I need at all).

I'm not sure how to fix the parser so that it will only parse
out the link, and leave the rest of the text alone,
regardless of the position of the link. I am using this
script to parse an XML string, so changing the input
source is not an option. Also, I must have the script in
JavaScript only (so Perl is not an option). I know that the
parsing problem can be remedied through multiple splits,
but I'm not sure where to go from here.

Any assistance would be greatly appreciated. Thank you.


Report Offensive Message For Removal

Response Number 1
Name: Elinor
Date: August 1, 2008 at 01:10:24 Pacific
Subject: Link Parser
Reply: (edit)

Hi,

How about:


function parseTextLinks(text)
{
var index=text.indexOf('http://');
if (index < 0) return text;

var tokens=text.split(" ");
var finalstr="";
for (var t=0; t<tokens.length; t++)
{
var index=tokens[t].indexOf('http://');
if (index < 0)
finalstr+=tokens[t];
else
finalstr+='<a onclick="window.open(\''+tokens[t]+'\')">'+tokens[t]+'';
if (t < (tokens.length-1))
finalstr+=' ';
}

return finalstr;
}

(Note: There should be a closing a tag instead of the '' in: '+tokens[t]+''; but short on time to investigate how to avoid this problem.)

hth

Elinor Hurst
http://elinorhurst.blogspot.com


Report Offensive Follow Up For Removal







Use following form to reply to current message:

   Name: From My Computing.Net Settings
 E-Mail: From My Computing.Net Settings

Subject: Link Parser

Comments:

 


  Homepage URL (*): 
Homepage Title (*): 
         Image URL: 
 
Data Recovery Software