How To Detect Whether A String Is In Url Format Using Javascript?
I think the question title seems to explain eveything. I want to detect whether a string is in URL format or not using javascript. Any help appreciated.
Solution 1:
Try this-
functionisUrl(s) {
var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/return regexp.test(s);
}
usage: if (isUrl("http://www.page.com")) alert("is correct") else alert("not correct");
Solution 2:
functionIsURL(url) {
var strRegex = "^((https|http|ftp|rtsp|mms)?://)"
+ "?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?"//ftp的user@
+ "(([0-9]{1,3}\.){3}[0-9]{1,3}"// IP形式的URL- 199.194.52.184
+ "|"// 允许IP和DOMAIN(域名)
+ "([0-9a-z_!~*'()-]+\.)*"// 域名- www.
+ "([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\."// 二级域名
+ "[a-z]{2,6})"// first level domain- .com or .museum
+ "(:[0-9]{1,4})?"// 端口- :80
+ "((/?)|"// a slash isn't required if there is no file name
+ "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$";
var re=newRegExp(strRegex);
return re.test(url);
}
Debuggex Demo (Improved version which matches also 'localhost')
Solution 3:
try something like this:
functionisUrl(s) {
var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)? (\/|\/([\w#!:.?+=&%@!\-\/]))?/return regexp.test(s);
}
Solution 4:
One for the future using the URL constructor and a basic try catch statement, it is supported in most modern browsers. Obviously no IE support...
constisUrl = (str) => {
try {
newURL(str);
returntrue;
} catch () {
returnfalse;
}
}
If the URL is valid it will get parsed by the constructor and return true.
If the string is not a valid URL the constructor will chuck a syntax error that will get caught and return false.
Solution 5:
Try this code. This expression is more complete and takes into account IP address:
functioncheckUrl(s) {
var regexp = /^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+$/return regexp.test(s); }
Post a Comment for "How To Detect Whether A String Is In Url Format Using Javascript?"