Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Validate Tutorialspoint URL via JavaScript regex?
To validate a TutorialsPoint URL using JavaScript, you can use regular expressions to check if the URL matches the expected domain pattern and extract specific parts of the URL.
Regular Expression Pattern
The regex pattern /^https?:\/\/(tutorialspoint\.com)\/(.*)$/ breaks down as follows:
-
^- Start of string -
https?- Matches "http" or "https" -
:\/\/- Matches "://" -
(tutorialspoint\.com)- Captures the domain (escaped dot) -
\/- Matches forward slash -
(.*)$- Captures everything after the domain until end of string
Example
function validateTutorialspointURL(myURL) {
var regularExpression = /^https?:\/\/(tutorialspoint\.com)\/(.*)$/;
return myURL.match(regularExpression) && myURL.match(regularExpression)[2];
}
console.log(validateTutorialspointURL("https://tutorialspoint.com/index"));
console.log(validateTutorialspointURL("https://tutorialspoint.com/java"));
console.log(validateTutorialspointURL("https://www.google.com/search"));
console.log(validateTutorialspointURL("http://tutorialspoint.com/javascript"));
index java false javascript
Enhanced Validation Function
Here's an improved version that provides more detailed validation results:
function validateTutorialspointURL(url) {
const regex = /^https?:\/\/(tutorialspoint\.com)\/(.*)$/;
const match = url.match(regex);
if (match) {
return {
isValid: true,
domain: match[1],
path: match[2] || 'root'
};
}
return { isValid: false };
}
// Test various URLs
const testUrls = [
"https://tutorialspoint.com/javascript/index.htm",
"http://tutorialspoint.com/java",
"https://www.tutorialspoint.com/python",
"https://google.com/search"
];
testUrls.forEach(url => {
const result = validateTutorialspointURL(url);
console.log(`${url}: ${JSON.stringify(result)}`);
});
https://tutorialspoint.com/javascript/index.htm: {"isValid":true,"domain":"tutorialspoint.com","path":"javascript/index.htm"}
http://tutorialspoint.com/java: {"isValid":true,"domain":"tutorialspoint.com","path":"java"}
https://www.tutorialspoint.com/python: {"isValid":false}
https://google.com/search: {"isValid":false}
Key Points
- The function returns the path portion when URL is valid, or
falsewhen invalid - Both HTTP and HTTPS protocols are supported
- The regex specifically matches "tutorialspoint.com" domain only
- URLs with "www." prefix will not match this pattern
Conclusion
Regular expressions provide an effective way to validate TutorialsPoint URLs and extract specific URL components. The validation ensures URLs match the expected domain pattern and can extract the path for further processing.
Advertisements
