Tips for extracting a specific segment from a URL string

Take a look at the outcome of the console.log below:

console.log('subscribe:', event.url);
"https://hooks.stripe.com/adapter/ideal/redirect/complete/src_1E2lmZHazFCzVZTmhYOsoZbg/src_client_secret_EVnN8bitF0wDIe6XGcZTThYZ?success=true"

I need to remove src_1E2lmZHazFCzVZTmhYOsoZbg and

src_client_secret_EVnN8bitF0wDIe6XGcZTThYZ

Can you guide me on how to accomplish this?

Answer №1

Transform the given string into a URL format, locate the pathname, and then divide it based on the / delimiter to extract the last two segments.

var str = "https://hooks.stripe.com/adapter/ideal/redirect/complete/src_1E2lmZHazFCzVZTmhYOsoZbg/src_client_secret_EVnN8bitF0wDIe6XGcZTThYZ?success=true"

const parts = new URL(str).pathname.split('/').slice(-2)
console.log(parts)

Answer №2

If the parameter ?success=true in the query is considered optional (which is usually the case), you might want to use the following JavaScript function:

function extractSrcAndSecret(url) {
  const regex = /\/(src_[^/?]+)\/(src_client_secret_[^/?]+)/.exec(url);
  return {
    src: regex && regex[1] || "",
    secret: regex && regex[2] || ""
  }
}

// Example:
const result1 = extractSrcAndSecret("https://hooks.stripe.com/adapter/ideal/redirect/complete/src_1E2lmZHazFCzVZTmhYOsoZbg/src_client_secret_EVnN8bitF0wDIe6XGcZTThYZ?success=true");
const result2 = extractSrcAndSecret("https://hooks.stripe.com/adapter/ideal/redirect/complete/src_1E2lmZHazFCzVZTmhYOsoZbg/src_client_secret_EVnN8bitF0wDIe6XGcZTThYZ");
const result3 = extractSrcAndSecret("https://hooks.stripe.com/adapter/ideal/redirect/complete");

console.log(result1, result2, result3)

Answer №3

let link = "https://hooks.stripe.com/adapter/ideal/redirect/complete/src_1E2lmZHazFCzVZTmhYOsoZbg/src_client_secret_EVnN8bitF0wDIe6XGcZTThYZ?success=true";


const result = link.split(/\?|\//g).filter(item => item.startsWith("src"));

console.log(result)

Answer №4

  let [x, y] = request.path.split("?")[0].split("/").slice(-2);

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

Invoking a Node.js function using a URL reference

Is there a way to call a function located in a remote URL? I have the page URL and the function name. The server-side application is running on NodeJs Express, and the function structure is as follows: function executer(param1, param2){ //logic re ...

Struggling with the conundrum of aligning a constantly changing element amid the

I was optimistic about the code I wrote, hoping it would work out in the end. However, it seems that my expectations might not be met. Allow me to provide some context before I pose my question. The animation I have created involves an SVG element resembl ...

What is the most efficient method for adding each unique unordered list element with a specific class to the nearest parent article tag

The current code structure looks like this: <article id="post-529"></article> <ul class="post-meta"></ul> <article id="post-530"></article> <ul class="post-meta"></ul> <article id="post-531"></a ...

Ways to implement a package designed for non-framework usage in Vue

Alert This may not be the appropriate place to pose such inquiries, but I am in need of some guidance. It's more about seeking direction rather than a definitive answer as this question seems quite open-ended. Overview I've created a package th ...

Deleting empty tags in an HTML h1 element with JavaScript

Is there a way to use JavaScript to remove empty h1 tags only? <h1>Hello World!</h1> <p>Lorem ipsum dolor sit amet</p> <h1></h1> <p>consectetur adipiscing elit.</p> <h1></h1> <p>Sed do ...

Cleve js does not include delimiters in its date output

In my Vue.js project, I decided to implement a date input field using cleave.js. After passing the following options: options="{date: true, delimiter: '/', datePattern: ['m', 'd', 'Y']}" I encountered an issue wh ...

Accessing Github REST API with Next-auth token

Looking to enable user login and retrieve specific user data using the Github REST API, such as repositories and issues. After successfully implementing the login feature, I encountered an obstacle with the Github REST API that requires a token for endpoi ...

Discovering elements that are currently visible in an Angular list

Suppose there is a variable named users which represents an array We have the following ng-repeat statement: ng-repeat="user in users | filterUser: searchUser: assignedUsers: selectedDivision" After filtering the users using searchUser and selectedDivis ...

AutoComplete issues a warning in red when the value assigned to the useState hook it is associated with is altered

const [selectedCountry, setSelectedCountry] = useState(); <Autocomplete autoHighlight={true} //required autoSelect={true} id="geo-select-country" options={availableCountries} value={se ...

Troubleshooting compilation problems in Angular2 with nested components

I have created two components in Angular2 using TypeScript: app/app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'my-app', styles : [` .parent { background : #c7c7c7; ...

Tips for Dynamically Binding Data in Angular ChartsWant to learn how to dynamically bind

I have integrated angular-charts directives into my application and everything works perfectly when initializing the data. However, I encountered an issue when reading the data from a JSON file and assigning it to the chart. The x-axis and y-axis are gener ...

Check if an element possesses a specific property and corresponding value in JavaScript

I was looking to determine if an object has a specific property with a certain value, and wanted to search for it within an array of objects. var test = [{name : "joey", age: 15}, {name: "hell", age: 12}] After testing the code snippet below, I realized ...

Utilizing the Spread Operator in combination with a function call within the props of the Tab component in Material UI

I came across this code snippet in Material UI: <Tab label="Item One" {...a11yProps(1)} />. It uses the spread operator (...) with a function call within the props. However, when I tried to use it separately like: console.log(...a11yProps(3 ...

Discover the process of retrieving an image from the backend with React and Node.js

Hey there! I'm currently working on a Housing blog using ReactJS and NodeJS. One of the tasks I tackled was creating a login controller in NodeJS to send user details, including the image path from the database, to the frontend. The image path is sto ...

What are the different ways to utilize the Angular Loading Bar for specific waiting scenarios?

In the project I am currently working on, navigation is primarily done through Ajax loading of HTML templates. The Angular Loading Bar feature is proving to be quite effective in this setup, as it employs interceptors to keep track of most $http requests. ...

Request the generic password prior to revealing the concealed div

I want to implement a feature where a hidden div is shown once a user enters a password. The password doesn't need to be stored in a database, it can be something simple like 'testpass' for now. Currently, I have written some code using Java ...

The mystery of the undefined return value in my Ionic v4 get function

I attempted to retrieve my location by saving the latitude and longitude, but my declared variable isn't returning anything. Take a look at my code snippet: public device_location: any = {}; constructor(private geolocation: Geolocation) { this.s ...

Can iPhone/iOS 6 users using Mobile Safari detect if the browser is in full-screen mode? How about compatibility with Android?

I am curious about detecting whether a user is using the "fullscreen feature" in Safari. I'm not referring to starting from the springboard, but rather the feature introduced in iOS 6. There was a similar query on SO where this code snippet was share ...

What could be causing the fourth tab to not show any data while the first three tabs are functioning as expected?

I've encountered an issue with my HTML tabs. While I can easily switch between the first three tabs and view their content, tab 4 doesn't seem to display its associated data. It's puzzling why tab 4 is not working when the others are functio ...

Looking to establish combinations in typescript? The answer lies in utilizing a discriminated union

I've been working with Typescript and I'm curious if it's possible to specify the valid combinations of input for a function. Below is a simplified version of the code: interface ActionType { type: string, payload: { count?: ...