w3resource

JavaScript: Return true if the given string is an absolute URL, false otherwise

JavaScript fundamental (ES6 Syntax): Exercise-207 with Solution

Check Absolute URL

Write a JavaScript program that returns true if the given string is an absolute URL, false otherwise.

  • Use RegExp.prototype.test() to test if the string is an absolute URL.

Sample Solution:

JavaScript Code:

// Define a function 'isAbsoluteURL' that checks if the input string is an absolute URL
const isAbsoluteURL = str => /^[a-z][a-z0-9+.-]*:/.test(str);

// Test cases to check if the input strings are absolute URLs
console.log(isAbsoluteURL('https://google.com')); // true (starts with 'https://')
console.log(isAbsoluteURL('ftp://www.myserver.net')); // true (starts with 'ftp://')
console.log(isAbsoluteURL('/foo/bar')); // false (does not start with a protocol)

Output:

true
true
false

Flowchart:

flowchart: Return true if the given string is an absolute URL, false otherwise

Live Demo:

See the Pen javascript-basic-exercise-207-1 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript program to check if a given string is an anagram of another string (case-insensitive, ignores spaces, punctuation and special characters).
Next: Write a JavaScript program to check whether the provided value is of the specified type.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/javascript-exercises/fundamental/javascript-fundamental-exercise-207.php