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.