What is the best way to display only the host and pathname of the links generated by Array.map()?

I am currently utilizing Array.map() to display a list of files in cache:

<div data-offline></div>
    <script>
    var version = 'v1:'; 
        if (navigator && navigator.serviceWorker) {
            caches.open(version + "pages").then(function (cache) {
                cache.keys().then(function (keys) {
                    var offline = document.querySelector('[data-offline]');
                    offline.innerHTML =
                    "<ul class=\"li-list\">" +
                    keys.map(function(key) {
                                    return '<li>› <a href="' + key.url + '">' + key.url + '</a></li>';
                                }).join('') +
                    "</ul>";
                });
            });
        }
    </script>

Thus, I have an overview of all html pages - given that the cache is specifically for html files - with their respective full URLs, such as "https://www.example.com/about/" etc.

My aim is to modify

<a href="' + key.url + '">' + key.url + '</a>
so that only the host (example.com) and pathname (/about/) are displayed within the text of the link

Unfortunately, I am unsure of how to carry out this implementation within this script.

Answer №1

To retrieve the hostname and pathname, you can apply the following method

const urlLink = document.createElement('a');
urlLink.href = key.url;

const { host, pathname } = urlLink;

This will transform your initial code snippet into

<div data-offline></div>
    <script>
    var version = 'v1:'; 
        if (navigator && navigator.serviceWorker) {
            caches.open(version + "pages").then(function (cache) {
                cache.keys().then(function (keys) {
                    var offline = document.querySelector('[data-offline]');
                    offline.innerHTML =
                    "<ul class=\"li-list\">" +
                    keys.map(function(key) {
                      const urlLink = document.createElement('a');
                       urlLink.href = key.url;
    
                       const { host, pathname }  = urlLink;
                                    return '<li>&rsaquo; <a href="' + host + '">' + pathname + '</a></li>';
                                }).join('') +
                    "</ul>";
                });
            });
        }
    </script>

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

The RouterView component seems to be malfunctioning within the Vue project

I recently started working on a vue-project where I created a Home page with a sideBar component and a routerView component. Here's a preview: https://i.sstatic.net/f51tdsZ6.png When clicking on any sidebar item, the router navigates to the corresp ...

Having trouble getting the Node.JS Express Server to function properly on Enide?

My webserver is built using Node.JS with express and has multiple route commands. While everything works fine when running Node from the command line, I encounter an issue when running it within the Enide environment. Each request triggers an error messa ...

What is the npm command in React to generate a new component?

As a newcomer to React, I am eager to learn how to generate a new component using a command. I am looking to replicate the functionality of the Angular 2 command "ng generate component Test" in React. After searching online, I came across a reference at ...

Updating a MongoDB document using only the data from checked checkboxes

Imagine having data structured like this: _id:60e2edf7014df85fd8b6e073 routineName:"test" username: "tester" monday:[{ _id: 60e430d45395d73bf41c7be8 exercise: "a" }{ _id: 60e4329592e ...

What is the best way to toggle the visibility of a dynamically created HTML element in ASP.NET?

I'm working on a program that displays two different prices depending on whether the user is registered or not. Registered users will see both the normal price and the discounted price, while unregistered users will only see the normal price. I need t ...

Exploring Deeply Nested Routing in Angular

I've been exploring the use of multiple router outlets and encountered an issue. When using the navigateBy function of the router, I am unable to view my child route and encounter an error. However, when I access it via the routerLink in HTML, I get ...

Is it possible to simultaneously run two Node.js projects on Windows?

Is it possible to run two Node.js projects on a Windows operating system? If so, what is the process for doing that? If not, can I run two Node.js projects on a dedicated host instead? ...

Tips for Creating an Upward-Dropping Dropdown Menu in HTML/JavaScript When Space is Limited on the Page

Hello, I am currently seeking a solution to adjust my dropdown menu so that it appears above instead of below when the page doesn't have enough space to display it fully. My tools for this project include HTML, Javascript, CSS, and JQuery exclusively. ...

How can you use jQuery to transform a H3 tag into a clickable link?

To transform the h3 tag into a clickable link with jQuery and set the href attribute, while preserving the H3 styling and adding an anchor tag, you can use the following code as an example: Click Here ...

Preserve the content in the text box corresponding to the selected radio button

In my form, there are multiple radio buttons, each with an associated text box value. Users can only select one radio button at a time and submit the form. However, sometimes users will enter data in a textbox for one radio button, then switch to another o ...

Set maximum size for background image in div

I'm facing some challenges with setting the maximum height of a background image within a div. I want the max height to be equal to the actual height of the image, without stretching it. Ideally, if there is excess content in the div, it should stop a ...

Update search results when performing a new search on a web application (without using jQuery)

My simple web app interacts with an API to retrieve search results from a database and utilizes ajax to insert them into an empty ul element on the page (employing JSONP for cross-domain requests). I am struggling to achieve this functionality using plain ...

Is there a way to trigger a "click" on a webpage without physically clicking? So that I can preview the response message before actually clicking

Is it possible to generate a "mock" request to a server through a website in order to examine the response before sending the actual request? Let me clarify with an example: if I were to click on a button on a website, it displays a certain message. I am ...

Apologies, but Discord.js is unable to access the property "user" of a null object

I am facing a perplexing issue that I cannot seem to wrap my head around. The function works perfectly on one server but fails on another. Below is the snippet of code in question: const user = message.author; let servericon = message.guild.iconURL; let se ...

Vertical Positioning of Tabs in Materialize CSS

My current challenge involves creating vertical tabs using materialize CSS, specifically in regards to positioning. The desired outcome is for the content to align at the same level when clicking on TAB 3. An example of the expected result can be seen in t ...

Validating the userid with jQuery before form submission

Currently, I am working on a form where I need to validate if the userID is already in use before allowing the user to submit it. After some research, I came across a solution on another website. However, when I tried to implement the code, I encountered ...

How to Automatically Display the First Tab in Bootstrap 3

Having a dynamic modal with two tabs, I aim for #tab1 to always be the default tab upon opening the modal. The issue arises when the modal is opened, #tab2 is clicked, and then the modal is closed. Subsequent reopenings still display #tab2. See JSFiddle e ...

Using AJAX to dynamically load Javascript

I came across this interesting code snippet: <script type="text/javascript" language="javascript"> $(function(){ $(window).hashchange( function(){ window.scrollTo(0,0); var hash = location.hash; if (hash == "") { hash="#main"; } ...

Using the v-for directive to create sequential lists

I am struggling to display pairs of data from an object based on category using nested v-for loops. The object, categoryArray, contains entries such as {stage 1, red}, {stage 1, blue}, {stage 2, orange}, {stage 3, brown}, {stage 2, green. My desired displ ...

Reposition the element at the bottom of its parent element

I am facing an issue with the HTML structure in my application: <div class="work-item"> <div class="image-container"> </div> <div class="text-container"> </div> </div ...