Reputation: 19
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<script type="text/javascript">
function create_urls(input)
{
var input = input.replace(/^((ht|f)tp(s?))\://([0-9a-zA-Z\-]+\.)+[a-zA-Z]{2,6}(\:[0-9]+)?(/\S*)?$/gim,'<a href="$&" class="my_link" target="_blank">$&</a>');
document.getElementById('disply_id').innerHTML = input;
}
</script>
</HEAD>
<BODY>
<input type="text" id="replace_id"/>
<input type="button" value="replace" onclick="create_urls(document.getElementById('replace_id').value);"/>
<div id="disply_id">
</div>
</BODY>
</HTML>
i want to find url's matching with "http://google.com" or https://www.google.com and place it in anchor tag
Thanks
Upvotes: 0
Views: 2647
Reputation: 4564
Taken from SELFHTML.org (German webpage) there's an example doing pretty much the same.
var input= "foo bar http://google.com";
input = input.replace(/((ht|f)tps?:\/\/\S*)/g, '<a href="$1">$1<\/a>');
this will match every URL starting with http, https or ftp protocol.
To deal with the restriction on just .com
and .tv
endings you could try this:
input.replace(/((\S*\.(com|tv))(\/\S*)?)/gi, '<a href="$1">$2<\/a>')
combining both patterns you could be looking for something like this: (some restrictions here)
input.replace(/((((ht|f)tps?:\/\/)?[^\/\s]+\.(com|tv))(\/\S*)?)/gi, '<a href="$1">$2<\/a>')
explained:
((ht|f)tps?:\/\/)? - optional http:// or https:// or ftp:// or ftps:// [^\/\s]+ - URL domain containing no slash and no whitspace \.(com|tv) - ending .com or .tv (not optional! you may want to add more) (\/\S*)? - optional rest of URL after domain
P.S. In your regex you didn't escape the //
by \/\/
update
I'd try this approach:
var regex = /((ht|f)tps?:\/\/\S*)/g;
var result = regex.exec(input);
if ( result != null && result.length > 1 ) {
input = '<a href="' + result[1] + '">' + result[1] + '<\/a>';
} else {
input = input.replace(/((\S*\.(com|tv))(\/\S*)?)/gi, '<a href="$1">$1<\/a>');
}
Upvotes: 2