Struggling to break down a URL into separate elements such as http:, www., stackoverflow, questions, and ask

While the input is working fine and producing the expected string output, I am struggling with creating arrays and not sure what to do next. Despite searching extensively, I have been unable to find a solution.

            <body>
<form>
    <fieldset>
        <legend>
            Url:
        </legend>
        <input type="url" ID="inputurl" value="please input a URL"> 
        <input type="button" onclick="PlaceUrl()" value="try me">

</fieldset>
</form>
<p id="URLdemo"></p>

<script>

    function PlaceUrl() {
        var x = document.getElementById("inputurl").value;
        document.getElementById("URLdemo").innerHTML = x;
         //outputs the string fine
        var arr1 = x.split(window.location.pathname);
        var arr2 = str.array (window.location.pathname.split(arr1));
        //this does nothing
     }

</script>

Answer №1

let link = 'https://stackoverflow.com/questions/59483624/trying-to-split-a-url-into-an-array-like-http-www-stackoverflow-questions-ask'
let parts = link.split(/[\.\\\/]/g)
console.log(parts)

// ["https:", "", "stackoverflow", "com", "questions", "59483624", "trying-to-split-a-url-into-an-array-like-http-www-stackoverflow-questions-ask"]

Answer №2

To effectively manage URLs, you have the option to utilize the URL() constructor.

When dealing with the current window or tab using window.location, keep in mind that it is limited to the specific site and cannot be used across different domains. In such cases, consider employing the URL() for better control.

var url = new URL('https://stackoverflow.com/questions/59483624/trying-to-split-a-url-into-an-array-like-http-www-stackoverflow-questions-ask#');

console.log('Host:', url.host);
console.log('Path name:', url.pathname);
console.log('Question id:', url.pathname.split('/')[2]);
console.log('Question title:', url.pathname.split('/')[3]);

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

Creating an array in Javascript and populating it with dynamically generated values

I am currently iterating through 3 arrays, searching for 'actionTimings' in each array and summing up the values of actionTimings (which are all numbers). How can I store these 3 values in a new array? This is what I have tried so far... $.each( ...

Experiencing significant delays in keyboard response when using an Angular application on mobile browsers such as Safari

Experiencing a frustrating delay in keyboard response when using an Angular app on mobile Safari and Chrome. Surprisingly, there are no such issues when typing on desktop browsers. Any suggestions for troubleshooting this problem? My hunch is that it may ...

Tips for positioning elements on an HTML page by utilizing CSS styling

I have a primary container with the following CSS: .major { width:30%; height:100%; position:absolute; } Now, I want to insert web information at the bottom part which includes: About | Terms | Policies | Contact Us This content will be within the .web ...

Ways to avoid multiple AJAX requests in PHP interfering with one another when updating the database

I am facing an issue with a JavaScript client that sometimes sends two AJAX requests to the server within milliseconds of each other. Unfortunately, I have no control over fixing this bug on the client side and can only handle it from the server side. The ...

My website crashed after attempting to update WordPress

After upgrading my website to Wordpress 3.4, I encountered a major issue that caused significant damage to my site. It seems that half of my posts were not accessible and resulted in a 404 error. Additionally, pages 3 and 4 of my posts also showed a 404 er ...

Issue with Collapse Feature on Bootstrap 3.x Navbar

The Bootstrap 3 Navbar expands properly in full screen and on a browser with a small width on a desktop PC and mobile browsers, but when using the Toggle navigation button, it doesn't slide down. I have tried to replicate the code from this example: h ...

Tips for modifying the input variables of the createControls function in JavaScript

I encountered an issue while working with a function createControls(){ return new THREE.TrackballControls( camera,domElement );} that was created using THREE.TrackballControls=function(object, domElement){.....} controls = createControls(camera, rende ...

What is the approach taken by NextJS for ensuring the security of pages when attempting to access them directly in the browser

What happens in NextJS when an unauthorized user tries to access secure pages directly in the browser? Currently, I am attempting to view the /dashboard (which is a secure page). The dashboard DOM elements are displaying. Please refer to the screenshot be ...

Using AJAX to retrieve a specific JSON object from an array of JSON data

Data retrieved in JSON array from the API: [{"id":"001", "name":"john", "age":"40"}, {"id":"002", "name":"jane", "age":"30"}] Using Ajax: $.ajax({ url: 'interface_API.php', ...

Managing an undetermined quantity of elements from a form in PHP

Currently developing an inventory page for my job. I've crafted a page that will iterate through my database and showcase all the items stored within. include 'auth.php'; //authentication required for login change $sql="SELECT * FROM `inven ...

Utilizing JSON format, handling special characters, and storing data in a database

My friend approached me with a question and although I wanted to offer immediate help, I realized that seeking advice from others may provide better solutions. Situation: Imagine there is a Form that includes a RichText feature: DHTMLX RichText (). This R ...

What steps should I follow to display three.js in a web browser?

Every time I attempt to view my progress with three.js on my local browser, it fails to load and gives me this error message, Uncaught TypeError: Failed to resolve module specifier "three". Relative references must start with either "/" ...

What are the steps for transferring data from a temperature sensor to an HTML document?

One useful command I use in the terminal is to display the temperature data from my sensor, which looks like this: cat /sys/bus/w1/devices/28-000005330085/w1_slave | grep "t=" | awk -F "t=" '{print $2/1000}'. I want to incorporate this sensor dat ...

tips for aligning figcaption vertically to image within figure

Is there a way to vertically align the text in the figcaption with the image in this figure? Check out an example here: http://jsfiddle.net/YdATG/1/ Here is the HTML code: <section class="links"> <a href="#"> <figure class="grid-pa ...

In Laravel Blade, I am looking to display a Modal popup and dynamically pass data based on the user's ID

When a user clicks on the "View Details" Button, I need to display a popup modal with information specific to that user. The data for each user is stored in the $user variable. I would like to achieve the same functionality as demonstrated on this website ...

What is the reason behind padding increasing the apparent width of an element, despite having box-sizing set to border-box?

While working with Semantic-ui, I encountered an issue with toggle boxes placed next to each other in a flexbox container. When the window size is reduced, the boxes wrap around so that one is positioned on top of the other. To create some spacing between ...

Can the ID attribute be used in the closing tag of an HTML element

Could this code be improved by properly closing the div with an ID: <html> <body> <div id="main"> </div id=main"> </body> </html> ...

What are some ways to render a React component when its ID is only determined after making an AJAX call?

Currently, I am working on developing a chat application where a chat message is immediately displayed (using a React component) once the user sends it by hitting the Enter key: https://i.sstatic.net/MJXLd.png https://i.sstatic.net/S6thO.png As shown in ...

Determine whether any property within the object is currently null

I am working with an array of objects called data, each object in the array having multiple properties, some of which may have null values. https://i.sstatic.net/hc5O3.png My goal is to filter through this array and eliminate any object that contains a p ...

Trouble aligning items within a flex-wrap parent using CSS flex-item's align-self functionality

I am facing an issue with my flex parent container. It is set to flex-wrap: wrap and justify-content: flex-end. Within this container, there is a flex-child called button-group that I want to align to the left using align-self, but it seems to not be worki ...