Retrieve the webpage address, search parameters, and anchor symbols

I have a form input where users enter a valid URL. My goal is to extract the URL, query string (if provided by the user), and hash value (if provided) separately.

This is what I currently have:

  var url = userInput.split('?')[0]; //get url
  var qs = userInput.split('?')[1].split('#')[0]; //get query string
  var hash = userInput.split('#')[1]; //get hash value

The issue arises when the user enters only a hash value without a query string.

http://example.com/some-page/ref?param=value#4567

Expectations are as follows:

URL: http://example.com/some-page/ref

Query String: ?param=value

Hash Value: #4567

Answer №1

It's always advisable to implement a try and catch block in your code.

try {
  let url = input_value.split('?')[0]; //extract URL
} catch (error) {
  let url = input_value;
}
try {
  let qs = input_value.split('?')[1].split('#')[0]; //extract query string
} catch (error) {
  let qs = "";
}
try {
  let hash = input_value.split('#')[1]; //get hash value
} catch (error) {
  let hash = "";
}

This approach helps prevent any unhandled Type Errors. For instance, using url = input_value as a fallback if no query string is present.

Console Output

https://i.sstatic.net/R9T8A.png

Below is a tailored solution for your specific use case:

https://i.sstatic.net/M5Q2W.png

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

Issue: The component series.line does not exist. Please ensure it is loaded before using it in Vue Echarts

I added the line component, but I'm still encountering issues. I set up my project using vue cli 3 and referred to this guide, but I can't locate the vue.config.js file in my project. Therefore, I manually created a vue.config.js and placed it in ...

How can I immediately disable a button upon clicking "cancel" on a modal that contains TextFields in React Version 18?

New to React development. Looking for a way to reset a button to its initial disabled state when canceling out of a modal. The scenario is that upon clicking a button, a dialog will appear with an "ADJUST" button that is initially disabled until text is ...

Update the content of an HTML element without having direct access to the HTML code

I am currently in the process of creating a website using a website builder, and I am interested in customizing the default message that is displayed when a required field in the website form is left empty. The form in question is an integral part of the w ...

The call stack in mongodb has surpassed its maximum size limit

I am currently executing a method. Method execution var message = "Hello" function1("78945612387", message, null, "Portalsms") Node JS Code function function1(mobileno,body,logExtraInfo,messageType){ request(uri, function (error, resp ...

Conflicting styles arise when using the makeStyles function from Material UI with imported

In working on a React component library using create-react-library, I have incorporated basic components that utilize Material UI components and the material UI hook-based styles pattern. For example (in a simplified form): // LibraryComponent.js const u ...

Attach a click event handler to a D3 element

Upon loading the page, the nodeClick() method is called without any clicking action. How can I adjust it so that the nodeClick() function is only triggered when I click on the element? Here is the code snippet: var node = svg.selectAll(".node") .on( ...

Create a file with jQuery and send it to PHP

Hello everyone, I am currently in the process of developing a website that has the ability to generate an MS Excel file using jQuery and allow users to download it. My question is, how can I pass this generated file to PHP so that it can be sent as an atta ...

What is the best way to achieve a full width table in an HTML format on a smartphone browser?

Apologies for my limited English proficiency. I am currently working on creating a horizontal scrollable table in HTML. My goal is to make the width of the table span beyond the browser's viewing area, so that sticky cell functionality can be implem ...

In the world of Knockout JS, forget about using e.stopPropagation() because it won't

In my table, I have two actions that can be performed: Click event on the row level and click while checking a checkbox inside that row. However, when the checkbox is checked, I do not want the click event on the row to be triggered. <tbody data-bin ...

Numerous Levels of Dropdown Menus

I am looking to implement a feature on a web page where users can select multiple vehicles using JQuery. The idea is that selecting the brand in the first dropdown will populate the second dropdown with the models available for that specific brand. The ...

Gaining entry to specialized assistance through an occasion

Having trouble accessing a custom service from a custom event. Every time the event is fired, the service reference turns out to be null. @Component({ selector: "my-component", template: mySource, legacy: { transclude: true } }) export class myComponent { ...

Having trouble organizing a list of objects based on changing keys

Below is the implementation of a custom pipe designed to sort records: import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'sortpipe' }) export class SortPipe implements PipeTransform { transfor ...

What are the pros and cons of using a piped connection for Puppeteer instead of a websocket?

When it comes to connecting Puppeteer to the browser, you have two options: using a websocket (default) or a pipe. puppeteer.launch({ pipe: true }); What distinguishes these approaches? What are the benefits and drawbacks of each method? How do I know wh ...

Check the email for accuracy and show as needed

I need help verifying email validity in JavaScript and displaying an alert box if it's invalid. If the email is valid, I want to display div2 instead. However, my current code doesn't seem to be working as expected. Below is the JavaScript code ...

Alter the onSeries property dynamically

If there are 3 different series identified by the IDs series1, series2, and flags, where initially the onSeries property of flags is set to series1. In a scenario where I click on the legend to hide series1, is it possible within the legendItemClick even ...

Develop a dynamic thunk and additional reducer to efficiently handle multiple API calls and retrieve data

Using Redux and Redux-Toolkit, I aim to streamline my code by implementing a single asynchronous Thunk and extra reducer for multiple requests. Below is the setup for both the company and client slices: import { createSlice, createAsyncThunk } from &apos ...

Experiencing difficulty incorporating JSON and JS into jQueryhandleRequestJSON and JS integration with jQuery

I'm having trouble fetching the 'sigla' field from a JSON file and inserting it into an HTML 'option object'. I could use some assistance with this issue, so if anyone out there can lend a hand, it would be much appreciated! Here ...

Retrieving JSON data without using Jquery's Ajax function

I was wondering if there is any way to retrieve the results of a jQuery AJAX call and store them in a traditional variable for use as a function. Here's an example: function getPoints(){ //An array of JSON objects var Points; ...

What is causing this async function to not throw an error with undefined?

In my asynchronous function, I am utilizing the fetch api to retrieve data and then updating my component state. The function includes two instances of the await keyword, allowing for seamless execution. Here is a breakdown of how this function operates: ...

The functionality of GET_POST is not functioning properly

I've encountered an issue with my PHP webpage and JavaScript function: function send_answer(){ $.ajax({ type: 'POST', url: '../path2file/file_mine.php', data: {dbf1:1, us:1, re:1}, success: relo ...