Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

RedExp to replace the URl 1

Status
Not open for further replies.

bean1234

Technical User
Nov 14, 2006
45
US
Hello Experts,

I am using a regular expression to replace a url typed in input with an anchor to display the input, I am using the following code, the RegExp works fine but the replace method cannot replace the matched text.Please advise.

Code:
<script>var test_match = /(((\b|^)https?:\/\/)([A-Za-z][^\b]*)+)|(((\b|^)www\.)([A-Za-z][^\b]*)+)/gi
var x="apple [URL unfurl="true"]www.xyz.com";[/URL]
alert(test_match.test(x));
alert(x.replace(test_match,"<a href=\"$1\" title=\"external link\">$1</a>"));
//alert(x);

</script>
 
Thanks I was able to resolve it but please advise on the efiiciency or correctness of the regular expression.

Thanks!
 
2 things I'll point out:

1. both instances of [!][^\b]*[/!] in your code could be replaced with [!]\B*[/!] to make the regexp slightly shorter.

2. The regexp checks to make sure that each domain starts with a letter, when this is not 100% valid. For example, googling for 123.com produced this:


This means you'll need to check for numbers as the start of each domain as well (among other characters possibly, I'm not sure of all the valid characters a domain can start with)

Here's the amended code for both suggestions:
Code:
var test_match = /(((\b|^)https?:\/\/)([A-Za-z[!]0-9[/!]][!]\B*[/!])+)|(((\b|^)www\.)([A-Za-z[!]0-9[/!]][!]\B*[/!])+)/gi

-kaht

[small](All puppies have now found loving homes, thanks for all who showed interest)[/small]
 
Thanks Kaht

Here's the modified RegExp

Code:
/((((\b|^)https?:\/\/)|((\b|^)www\.))(([A-Za-z\d][\B]*)+))/gi
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top