Reassemble the separated string while skipping over every other element in the array created by splitting it

Currently, I am working on the following URL: demo.example.in/posts/0ewsd/13213

My goal is to extract the hostname (demo.example.in) and the path (posts/0ewsd/13213) from this URL.

urlHost = 'demo.example.in/posts/0ewsd/13213';
let urlHostName = urlHost.split("/");

Even after using the split() method, the entire URL gets split into different parts...

['demo.example.in', 'posts', '0ewsd', '13213']

What I actually want is to separate demo.example.in and posts/0ewsd/13213. Is there any alternative approach that can help achieve this?

Answer №1

If you're looking for a solution, one approach is to utilize the String.match() method along with the regular expression pattern /^([^/]*)\/(.*)$/ and capturing groups:

const url = "demo.example.in/posts/0ewsd/13213";

const customSplit = (url) =>
{
    let matches = url.match(/^([^/]*)\/(.*)$/);
    return [matches[1], matches[2]];
}

let [hostname, path] = customSplit(url);

console.log("hostname => " + hostname);
console.log("path => " + path);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

Alternatively, another option is to use String.split() in combination with Destructuring Assignment:

const url = "demo.example.in/posts/0ewsd/13213";

const customSplit = (url) =>
{
    let [hostname, ...path] = url.split("/");
    return [hostname, path.join("/")];
}

let [hostname, path] = customSplit(url);

console.log("hostname => " + hostname);
console.log("path => " + path);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

Answer №2

If you're looking to extract specific parts of a URL, you can utilize a regular expression to do so. The regex pattern will match and capture anything except a forward slash (the hostname), then it will match a slash, and finally, it will capture the rest of the line (the path). This way, the hostname will be stored in the first captured group, while the path will be stored in the second captured group:

const input = 'demo.example.in/posts/0ewsd/13213';
const [, hostname, path] = input.match(/([^/]+)\/(.*)/);
console.log(hostname, path);

Answer №3

const websiteURL = 'example.demo.com/articles/789wdw/13456';

const [domain, parameter] = [websiteURL.substring(0, websiteURL.indexOf('/')), websiteURL.substring(websiteURL.indexOf('/') + 1)];

console.log(domain, parameter);

Trust this information proves useful to you!

Answer №4

To tackle this issue, utilize the powerful feature of regular expression grouping. The provided regEx will categorize the string into three distinct groups: first the host, followed by the delimiter (/), and finally the path.

var pattern = /^([\w\.]*)(\/)(.*)$/gim;

Check out the Demo here

Answer №5

To easily extract the host and path from a URL, consider adding the scheme to the beginning of the URL and utilize the URL API.

const url = new URL('http://' + 'demo.example.in/posts/0ewsd/13213');
const host = url.host, path = url.pathname.slice(1);

console.log('Host:', host);
console.log('URL Path:', path);

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

Viewing saved information prior to saving - JavaScript

I'm looking for a solution to allow users to preview captured records before they are inserted. Any suggestions on how to achieve this? HTML.html <form id="view" method="POST" class="formular"> <label>Name</label> ...

What is the best way to eliminate the border color on a drop-down menu's bottom border?

I need help removing the border color from a dropdown with the style border-bottom: 1px solid rgba(0, 0, 0, 0.42); After debugging, I discovered that it is originating from the class MuiInput-underline-2593. However, the CSS class MuiInput-underline-2593 ...

When trying to use the `map: texture` with a new `THREE.Texture(canvas)

i'm trying to apply the texture from new THREE.Texture(canvas) to the PointsMaterial, but it's not working as expected. The canvas appears on the top right corner, however, only white points are visible in the CubeGeometry. var texture = new ...

If a particular <td> element is present on the page, exhibit a unique <div>

I have a webpage with various HTML elements. <div class="alert">Your message was not sent.</div> <p class="pending">Email Pending</p> I would like to display the div.alert only if the p.pending is present. Is ...

Creating space between flex items in Slick Carousel with Vue

This is my current Slick Carousel. There are 4 items in a row, and I am looking to insert some margin between each item while maintaining the existing aspect-ratio: 1.3/1; I'm struggling with overriding the classes from vue-slick-carousel. Does any ...

Redirecting with Express js when the cookie is not found

I successfully integrated Facebook login using Passport-js and also set up Cookie-strategy for traditional username/password login on my Express-js backend with a React front-end. The backend and frontend are hosted on separate servers and domains (backend ...

Highlighting a Table Column with a Radio Button

I am struggling with controlling the highlight of a table using only radio buttons. When I try to change the selector to input:radio, it doesn't work as expected. It seems to only work with the selector provided in my code snippet. $("th").on("clic ...

Ways to obtain the <a> using the title attribute

Is there a way to remove 3 classes from a specific <a> element that is dynamically generated? The only constant is the title. How can I locate an element based on its title? I've searched online but haven't found exactly what I'm looki ...

comprehending the concept of express and mastering its usage

Can you confirm if my understanding is correct? 1) So, when I write this line of code... const express = require(“express”) I am assigning a "Class" to the variable express. 2) And then, when I call this function... express.jason() Am I correctly ...

Styling a Pie or Doughnut Chart with CSS

I am working on creating a doughnut chart with rounded segments using Recharts, and I want it to end up looking similar to this: Although I have come close to achieving the desired result, I am encountering some issues: Firstly, the first segment is over ...

SignalR 2.2 users are experiencing a lack of message reception

I have developed a unique self-hosted SignalR application that is operating within the framework of a console application. To access the hubs within this application, I have implemented a wrapper class to avoid referencing the SignalR.Core assemblies direc ...

Is there a way to verify the content of a span and automatically guide the user elsewhere if it meets certain criteria?

Currently, I am facing an issue with adding Google authentication to my website as the redirect function is not working properly. As a solution, I plan to implement manual redirection using JavaScript in case the value of the span element is <span id= ...

The Javascript code is functioning properly in Chrome, however, it is experiencing compatibility issues in other

Recently, I put together a simple web page using React and Express. One of the modules features a basic form with text input fields, an email input field, and a submit button that is supposed to send an email containing data from the input fields to me. To ...

What is the name attribute of an ES2015 function?

var individual = { announceIdentity() { console.log(this.identity); }, get firstID() { return "Superman"; } }; individual.announceIdentity.identification // "identity" individual.firstID.identifier // "get firstID" I recently came acros ...

Handling an Express server that receives a request with no data

I'm struggling with a problem where I am unable to retrieve a basic JSON object. When I log it to the console, all I see is {}. Let me showcase the server code below: const express = require("express"); const app = express(); app.listen(3000); app.us ...

When employing the map function in React, the resulting array is always equal to the last element within

Recently delving into the world of React, I encountered an issue while trying to assign unique ids to an array of objects within a Component's state using the map function. Strangely, despite my efforts, all elements in the resulting array ended up be ...

Running NPM module via Cordova

After developing an app using cordova, I encountered a challenge where I needed to incorporate a node module that lacked a client-side equivalent due to file write stream requirements. My solution involved utilizing Cordova hooks by implementing an app_run ...

Unable to establish successful Ajax connection with PHP function

I'm encountering an issue with submitting a form through ajax and I can't seem to figure it out: Ajax - samepage <script type="text/javascript"> $(document).on('submit','.subscribe',function(e) { $.ajax({ url: &apo ...

Error message 'AVV_ERR_PLUGIN_NOT_VALID' encountered within fastify

I've encountered an issue while setting up the environmental variables in my fastify - react app. Can someone help me with resolving the 'AVV_ERR_PLUGIN_NOT_VALID' error that I'm receiving for the following fastify code? Your assistance ...

I'm experiencing an issue where using .innerHTML works when viewing the file locally, but not when served from a web server. What could be causing this discrepancy?

Utilizing mootool's Request.JSON to fetch tweets from Twitter results in a strange issue for me. When I run the code locally as a file (file:// is in the URL), my formatted tweets appear on the webpage just fine. However, when I serve this from my loc ...