How To Find If A Text Contains Url String
Solution 1:
functionreplaceURLWithHTMLLinks(text)
{
var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;return text.replace(exp,"<a href='$1'>$1</a>");
}
Solution 2:
While the code above works good if all given URLs are full (http://mydomain.com), I had problems parsing a URL like:
www.mydomain.com
i.e. without a protocol. So I added some simple code to the function:
var exp = /(\b(((https?|ftp|file|):\/\/)|www[.])[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
var temp = text.replace(exp,"<a href=\"$1\" target=\"_blank\">$1</a>");
var result = "";
while (temp.length > 0) {
var pos = temp.indexOf("href=\"");
if (pos == -1) {
result += temp;
break;
}
result += temp.substring(0, pos + 6);
temp = temp.substring(pos + 6, temp.length);
if ((temp.indexOf("://") > 8) || (temp.indexOf("://") == -1)) {
result += "http://";
}
}
return result;
If someone should fine a more optimal solution to add a default protocol to URLs, let me know!
Solution 3:
You have to use regex(Regular expressions) to find URL patterns in blocks of text.
Here's a link to same question and answers: Regular Expression to find URLs in block of Text (Javascript)
Solution 4:
I tweaked dperinis regex-url script so that a URL embedded in a string can be found. It will not find google.com, this is necessary if it's a user input field, the user might leave out the whitespace after a period/full stop. It will also find www.google.com, since hardly anyone types the protocol.
(?:((?:https?|ftp):\/\/)|ww)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,}))\.?)(?::\d{2,5})?(?:[/?#]\S*)?
I tested it on www.regextester.com, it worked for me, if you encounter a problem, please comment.
Solution 5:
you can use a regular expression to find an URL and replace it by the same with a leading and a trailing tag
Post a Comment for "How To Find If A Text Contains Url String"