Ways to extract a number that comes after a specific word in a URL

I have a URL and need to extract a specific value from it by removing a certain step. I am looking for a regex solution to accomplish this task

For example, if I have the window.location.href, the URL might look like this:

https://mypage/route/step-1/more-route/
https://mypage/route/step-5/more-route/

I am seeking advice on how to use regex to extract the step value from these URLs. Any suggestions would be appreciated.

Thank you!

Answer №1

To keep the step number intact, you can utilize the replace method:

.+\/step-(\d+)\/.+

const link1 = 'https://mywebsite/path/step-7/more-path/'
const link2 = 'https://mywebsite/path/step-10/more-path/'

const extractStep = (link) => link.replace(/.+\/step-(\d+)\/.+/, '$1')

console.log(extractStep(link1))
console.log(extractStep(link2))

Answer №2

Divide it into smaller parts and then access them using the index.

const link = window.location.href;
 const linkArray = link.split('/');
 console.log(linkArray[4])

Answer №3

Here is a regular expression you can use:

\/step-(\d+)
  • \/ - Matches the forward slash character /
  • step- - Matches the word "step-"
  • (\d+) - Matches one or more digits (captured as a group)

let urls = ['https://mypage/route/step-1/more-route/'
,'https://mypage/route/step-5/more-route/']

let getStep = (url) => {
  let match = url.match(/\/step-(\d+)/i)
  return match && match[1]
}

urls.forEach(url=> console.log(getStep(url)))

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

Defining a Global Variable using the jQuery $(this)

I have been looking for ways to simplify my coding process, and one method I've tried is assigning a global variable. var parent = $(this).parent().parent().parent(); var parentModule = $(this).parent().parent().parent().parent(); Throughout my code ...

Tips for showcasing personalized validation alerts with jQuery in the HTML5 format?

One of the Javascript functions I designed is for validating file extensions before uploading: function validateFileExtension(field, extensions){ file_extension = field.val().split('.').pop().toLowerCase(); if ($.inArray(file_extension,exten ...

I'm looking to create a unique combination of a line and bar chart. Any advice on how to

When I stretch my Scale like this determineDataLimits: function () { var min = Math.min.apply(null, this.chart.data.datasets[0].data) console.log(this) console.log(defaultConfigObject) Chart.options.scales.rightSide.ticks.min = function ...

Create a drag-and-drop interface and link elements together using a custom JavaScript library

Seeking a solution or Javascript library to create a scientific modeling application, similar to flowchart software such as Visio. The ability to add elements and connect them by clicking and dragging is essential. https://i.stack.imgur.com/vSZpB.png The ...

In Visual Studio, the .js.map files and .js files seem to be mysteriously hidden, leaving only the TypeScript .ts files visible

In the past, I utilized Visual Studio Code for Angular 2 development and had the ability to hide .js and .js.map files from the IDE. Now, I am working on a project using VS 2017 Professional with Typescript, Jasmine, Karma, and Angular 4. Task Runner, etc. ...

Utilize AngularJS to interact with RESTful web services

Here is the JSON data fetched from my web service: [{"cameraid":"ggh","timestamp":"2016/05/10 01:31","filename":"ffffpg"}, {"cameraid":"mason","timestamp":"2016/05/10 05:31","filename":"aaa.png"} This is the HTML code I have: <!doctype html> <h ...

Invoke an RxJs observable to handle errors and retry the process

I have an observable called submit$ that submits a form. If this observable encounters an error with status code 403, it means the user is not authorized and needs to log in first. Is there a way to automatically trigger another observable when a specific ...

Main.js in Electron cannot find the NODE_ENV environment variable

Currently, I am in the process of developing an application which involves: React 16.4.0 Electron 2.0.2 Webpack 4.11.0 After successfully compiling and running the app using webpack (webpack dev server), my focus now shifts to showing only Chr ...

Updating nested forms in Angular 4

The nested form structure I am working with is a 'triple level' setup: FormGroup->ArrayOfFormGroups->FormGroup At the top level (myForm): this.fb.group({ name: '', description: '', q ...

Utilizing the real module instead of resorting to mock usage

I've configured Jest as follows: jest: { configure: { testEnvironment: 'jsdom', preset: 'ts-jest', transform: {...}, moduleNameMapper: { antd: '<rootDir>/__mocks__/antd/index.tsx&apo ...

A step-by-step guide on showcasing Flickr images through API using a Justified Gallery

I am looking to integrate the Miromannino Justified Gallery () into my project, but I want it to showcase images fetched from Flickr. I have successfully implemented the code to retrieve photos from Flickr using the API through Ajax: $.ajax({ url ...

Using Vue.js, you can set a method to return data directly to

Having just begun my journey with Vue, I find myself in a bit of a predicament. As part of my learning process, I am developing an app for tracking episodes in TV series. The initial step involves searching for series and adding them to a database. When co ...

Ways to verify the presence of an empty array object

I'm trying to determine whether all arrays inside an object are empty. To illustrate, consider the following object: var obj = { arr1: [0, 1, 2], arr2: [1, 2, 3], arr3: [2, 3, 4] }; After pop()ing values from the arrays within the object, I ...

Errors have been observed when using JavaScript variables that begin with the symbol $

For the longest time, I've used JavaScript variable names that begin with $ to signify that they hold jQuery values. For example: $buttons = $( 'button' ); However, a couple of nights ago, I encountered an issue when loading the page in the ...

The jQuery script automatically triggers submission on its own

Does anyone have an idea why the form auto-submits itself? I can't figure out why it's doing that. I'm using query parsley to validate the form in a modal. When a user opens the modal and starts typing in the text area, they must type at l ...

Django and its compatibility with modal windows

I have developed a Django website that includes multiple items in a "for" loop. I need to delete a specific item by opening a modal window and passing the post ID (referred to as "get_post_id") to the modal window. However, I want the modal window to exist ...

What could be causing the repetition of the same cookie in my request header when using jQuery ajax?

Stuck in a dilemma for hours now, seeking assistance or suggestions from anyone who can help me out. To sum it up, I have an asp.net web api application where I am trying to fetch data from a web api and populate multiple dropdown lists on a page using jQ ...

Which specific element should the userEvent.type(...) function target in order to work effectively with MUI's DesktopDatePicker TextField component?

Is there a way for me to input text into the TextField input within the MUI datepicker using react-testing-library's user-event? I've noticed that there is a mask applied to the input. I attempted to use userEvent.type(inputEl, '1') an ...

What could be causing my SectionList to occasionally display only a single section?

I'm facing a problem with the SectionList component where it occasionally fails to display all sections, only rendering the first one. After some debugging, I may have found a solution, but I'm unsure why it resolves the issue. While my page con ...

The next-auth/discord callbacks do not make any changes to the data

Currently, I am utilizing the next-auth/discord and facing an issue with the session callback not setting the user id to the session property as expected. [...nextauth].js import NextAuth from "next-auth/next"; import DiscordProvider from " ...