Identify if the string refers to a local file or an external file

Is there a way to distinguish between a local path and a reference to another server using JavaScript?

Given the list of URLs below, how can I identify which ones point to files on the local file system versus those leading to example.com?

var paths = [
    'foo/bar.css',
    '/bar/foo.css',
    '//cdn.example.com/monkey.css',
    'https://example.com/banana.css'
];

I have reviewed the url npm package, but it does not parse the third URL correctly to extract the host information.

My goal is to gather CSS details from a webpage as well as linked stylesheets, using a script that only has access to the page's URL. I need to determine if subsequent requests should be sent to the original host or another like example.com.

Answer №1

In order to accurately interpret a reference-URI, it is essential to have a base URL that serves as a point of reference.

For instance, in your particular scenario:

var url = require("url");
var baseUrl = 'http://www.example.com/base'; // please input the correct base URL here
var paths = [
    'foo/bar.css',
    '/bar/foo.css',
    '//cdn.testsite.com/monkey.css',
    'https://testsite.com/banana.css'
];
paths.forEach((p)=>{
    console.log(url.parse(url.resolve(baseUrl,p)).hostname);
});

Answer №2

To easily verify if a string contains http:// or http://, you can include other search strings like ftp://, etc.

var paths = ['foo/bar.css',
             '/bar/foo.css',
             '//cdn.example.com/monkey.css',
             'https://example.com/banana.css'];
             
paths.forEach(function(url){
  var result = (url.indexOf("http:") === 0 || 
                url.indexOf("https:") === 0 ||
                url.indexOf("//") === 0 && 
                (window.location.protocol === "http:" || window.location.protocol === "https:")) 
                ? "" : " NOT";
  console.log(url + " is" + result + " an external path");
});

Answer №3

To tackle this problem, one approach could be iterating through the array and utilizing a series of conditional statements. Here is an example in pseudo-code:

function analyzeURL(string) {
    if(string.contains("https://"))
    if(string.charArray[0] == "/" && string.charArray[1] == "/")
    if(string.charArray[0] == "/" && !string.charArray[1] == "/")
    if(string.charArray[0] != "/")
}

By implementing these conditional checks, you can segregate the strings into distinct functions for individual processing. Building such logic from scratch can often be more beneficial than relying on external libraries.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to add data to my collection using the main.js file on the server side in a Meteor application

I am a beginner with Meteor and trying to customize the tutorial codes. I have a code that listens for packets on my server-side main.js. Now, I need to store the data printed on the console into my database collection. import { Meteor } from 'meteor/ ...

The concept of overloading operators in V8

Here's a question that I've been pondering, but couldn't seem to find any answers for on Google. While it may not be achievable in pure JavaScript, let's say I'm developing a container class in V8 and then returning that class bac ...

What is the best way to test an externally hosted application with Testacular and AngularJS?

I have a Pyramid app running on http://localhost:6543. This app serves the AngularJS app at /. This app utilizes socket.io. The query is: Can I test this application using these tools? In my scenario.js file, I have the following: beforeEach(function( ...

Tips for modifying the value of a JSON object using Javascript or Jquery

I am looking to retrieve the value of a specific key, potentially accessing nested values as well. For example, changing the value of "key1" to "value100" or "key11" to "value111. { "key1": "value1", "key2": "value2", ...

Learn how to successfully place a draggable object into a sortable container while ensuring that the dropped item is a personalized helper element rather than the original object

The jQuery draggable/sortable demo showcases the process of dropping a clone of the draggable item (both draggable and sortable elements share the same structure). However, I am interested in dropping a different DOM structure. For example, when dragging a ...

Understanding how to activate a React navbar button is essential for creating a seamless user

How can I make my sidebar button change color when I navigate to the page it links to? ...

Executing several Ajax requests at once can decrease the speed of the process

When I make simultaneous API calls using Ajax, the process seems to be slow as JavaScript waits for all API responses instead of fetching them asynchronously. For instance, /api/test1 usually responds in 5 seconds and /api/test2 also responds in 5 seconds ...

Dynamically inserting templates into directives

I've been attempting to dynamically add a template within my Angular directive. Following the guidance in this answer, I utilized the link function to compile the variable into an HTML element. However, despite my efforts, I haven't been success ...

Experiencing difficulties establishing a connection between the React client and Node.js server using SocketIO

I am currently getting familiar with socketIO and have successfully set up a basic nodejs server. However, I am facing an issue where my nextJS app is unable to connect to the server as expected. Despite no errors being displayed, the messages that should ...

What is the best way to postpone one of the 3 ajax requests?

Can anyone assist me with handling AJAX forms? I am trying to ensure that the smallest one is executed after the others, but I also want to introduce a delay in the process. I attempted to utilize setTimeout(), however, it does not seem to be functioning ...

Having trouble with opening and closing popup windows in JavaScript while using Android frames?

To display additional information for the user, I create a new tab using the following code: window.open("/Home/Agreement", "_blank"); Within the Agreement View, there is a button with JavaScript that allows the user to close the Popup and return to the m ...

When sending a response using res.send, it is not possible to include all properties of

I'm working with an API controller method that looks like this: let object = { "key1": "value1", "key2": "value2", "arrayKey": [ { "arrKey": "arrValue", "arrKey1": 1 } ] } export const foo = ...

Could you explain the distinction between Node.bind() and Template Binding?

Currently, I am exploring the documentation for Google Polymer and have come across two types of data binding - Node.bind() and Template Binding. Can someone please explain the distinction between Node.bind() and Template Binding to me? ...

How can I pass standard HTML as a component in React?

I need help creating a Higher Order Component (HOC) that accepts a wrapper component, but allows me to pass standard HTML elements as inner content. Here is an example of what I want to achieve: type TextLike = string | {type,content} const TextLikeRender ...

Using Three.js to extract Vertex Colors based on the z-coordinate of Vectors

Here is a sample: http://jsfiddle.net/c3shonu7/1/ The code demonstrates the creation of a BufferGeometry object by cloning an IcosahedronBufferGeometry's vertices. The goal is to apply a color gradient to the subdivided icosahedron, with lighter shad ...

Creating an interactive Google line chart in MVC4

I am currently working on a dynamic line chart that needs to be able to adjust the number of lines (Standard, Latest, Earliest, Average) based on the database records. My code structure is similar to this example. function drawChart() { var data = ...

Tips for resolving asynchronous s3 resolver uploads using Node.js and GraphQL

My goal is to upload an image and then save the link to a user in the database. Below is my GraphQL resolver implementation: resolve: async (_root, args, { user, prisma }) => { .... const params = { Bucket: s3BucketName, ...

Steps to fix issues with Cross-Origin Read Blocking (CORB) preventing cross-origin responses and Cross Origin errors

var bodyFormData = new FormData(); bodyFormData.set("data", "C://Users//harshit.tDownloads\\weather.csv"); bodyFormData.set("type", "text-intent"); //axios.post("https://api.einstein.ai/v2/language/datasets/upload", axio ...

Arrange objects in an array by the date field using Meteor

I have updated my user collection in my Meteor app with an array of objects named contacts. This is how it looks now: { "_id" : "p6c4cSTb3cHWaJqpG", "createdAt" : ISODate("2016-05-11T11:30:11.820Z"), "services" : { ..... }, ...

Tips for managing a Yes No dialogue box that appears when a button is clicked with JavaScript

When the user clicks on the update button in my form, I want to prompt them with a message asking if they want to delimit the record using Yes and No buttons. If they click on Yes, then the code to delimit the record should be executed; otherwise, just upd ...