Languages
[Edit]
EN

JavaScript - check if URL is internal

9 points
Created by:
Reilly-Collier
860

In this short article, we would like to show how to use JavaScript, to check if URL is internal.

As an internal URL we understand the URL that indicates some webpage or resource on the same website on what was placed.

Practical example:

// ONLINE-RUNNER:browser;

const ORIGIN_EXPRESSION = /^https?:\/\/[^/?#]+/i;

const compareStrings = (a, b) => a.toLowerCase() === b.toLowerCase();

const isInternal = (url, origin = location.origin) => {
    if (url == null) { // null or undefined
        return false;
    }
    if (url === '') {
        return true;
    }
    const match = url.match(ORIGIN_EXPRESSION);
    if (match) {
        return compareStrings(origin, match[0]); // web page origin === indicated url origin
    }
    return true;
};


// Usage example:

console.log(isInternal(''));                   // true
console.log(isInternal('/snippets'));          // true
console.log(isInternal('?parameter=value'));   // true
console.log(isInternal('#anchor'));            // true
console.log(isInternal('robots.txt'));         // true
console.log(isInternal('/path/to/file.txt'));  // true

console.log(isInternal('https://dirask.com'));           // true
console.log(isInternal('https://dirask.com/snippets'));  // true

console.log(isInternal('https://google.com'));           // false
console.log(isInternal('https://google.com/about'));     // false

Note: the solution uses location.origin property that is available in web browsers only.

Note: in the above example, URLs are tested as internal, according to the current origin - Dirask origin.

 

Custom origin cases

URL can be internal according to indicated origin.

It means:

Practical example:

const diraskOrigin = 'https://dirask.com';

console.log(isExternal('https://dirask.com', diraskOrigin));           // true
console.log(isExternal('https://dirask.com/snippets', diraskOrigin));  // true


const googleOrigin = 'https://google.com';

console.log(isExternal('https://google.com', googleOrigin));           // true
console.log(isExternal('https://google.com/about', googleOrigin));     // true

 

See also

  1. JavaScript - check if URL is external

Alternative titles

  1. JavaScript - check if link is internal
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join