Regex explanation:
Sure! Let’s break down the regular expression used in the isURL function:
regex
^(?:\w+:)?\/\/([^\s.]+.\S{2}|localhost[\:?\d])\S$
^: Asserts the start of the string.
(?:\w+:)?: This part (?: ... )? is a non-capturing group that matches the protocol part of the URL, like http:// or https://. \w+ matches one or more word characters (letters, digits, or underscores), and : matches the colon. The ? makes this whole group optional.
\/\/: Matches the two forward slashes (//) after the protocol.
([^\s\.]+\.\S{2}|localhost[\:?\d]*): This part captures the domain name. Let's break it down further:
[^\s\.]+: Matches one or more characters that are not whitespace or a dot. This ensures that the domain name doesn't start with a dot or contain whitespace.
\.: Matches the dot separating the domain name.
\S{2}: Matches exactly two non-whitespace characters. This ensures that the domain name ends with a top-level domain like .com, .org, etc.
|: The pipe character serves as an OR operator, allowing for an alternative match.
localhost[\:?\d]*: Matches if the domain name is "localhost" followed by an optional port number. [\:?\d]* matches zero or more occurrences of a colon followed by digits (port number).
\S*: Matches zero or more non-whitespace characters after the domain name. This is to ensure that there are no trailing spaces or characters after the URL.
$: Asserts the end of the string.
function isURL(str) {
// Regular expression for URL validation
var urlPattern = /^(?:\w+:)?\/\/([^\s\.]+\.\S{2}|localhost[\:?\d]*)\S*$/;
return urlPattern.test(str);
}
// Example usage:
var myString = "https://www.example.com";
if (isURL(myString)) {
console.log("Valid URL");
} else {
console.log("Invalid URL");
}