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:


For more Practice: Solve these Related Problems:

  • Write a JavaScript program that returns true if a string starts with a valid protocol (http, https, ftp) indicating an absolute URL.
  • Write a JavaScript function that uses regular expressions to test if a URL is absolute.
  • Write a JavaScript program that checks if a URL string contains a valid domain and protocol.
  • Write a JavaScript function that validates URL format and returns true if it’s an absolute URL.

Go to:


PREV : Check Anagram.
NEXT : Check Specified Type.

Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.