Leveraging JQuery to extract the numerical value located between the slashes within a hyperlink

I need to extract numeric values from a link like this.

For example:

/produkt/114664/bergans-of-norway-airojohka-jakke-herre

In this case, I want to fetch 114664.

To achieve this, I have written the following jQuery code:

jQuery(document).ready(function($) {
    var outputv = $('.-thumbnail a').map(function() {
        return this.href.replace(/[^\d]/g, '');
    }).get();
    console.log( outputv );
});

https://jsfiddle.net/a2qL5oyp/1/

The problem I am encountering is when the URL contains additional characters like this:

/produkt/114664/bergans-of-norway-3airojohka-3jakke-herre

In this scenario, my code returns "11466433" due to the extra character "3". However, I only require the numeric value 114664.

Is there a way to extract only the numeric values after /produkt/?

Answer №1

If you are confident that the link structure will always follow the pattern outlined in your question, then it is advisable to proceed as follows:

let path = '/product/114664/bergans-of-norway-airojohka-jacket-men';
let id   = path.split('/')[2];

By using this method, you can easily extract the desired value from the array created by splitting the string at each '/' character.

Answer №2

If you're seeking the numerical portion following /product/ (regardless of its location) utilize a regular expression to search within the string:

var str = '/produkt/114664/bergans-of-norway-3airojohka-3jakke-herre';
alert(str.match(/\/product\/(\d+)/)[1])

(Please ensure in your actual code that .match() returned a valid array before attempting to access [1])

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

What is the best way to use Jquery to enclose a portion of a paragraph text within a

How can I wrap the content inside a span that comes after another span, inside a paragraph and a new span? To further illustrate this, consider the following example: <p>foo <span>bar</span> baz</p> The desired outcome is: <p& ...

Exploring jasmine-node: unraveling the mysteries of errors

As I embark on my journey to learn JavaScript, I decided to tackle some exercises on exercism.io. This platform provides pre-written tests that need to be passed. While things were going smoothly initially, I hit a roadblock with the latest exercise where ...

Unable to call a basic object's prototype method

Just starting out with node and feeling like I might be overlooking something simple. In my model file, I have a class that creates new object instances in the following way: const mongodb = require('mongodb'); const getDb = require('../util ...

JavaScript - Issue encountered while reaching the bottom of the webpage

While conducting tests using Firebug/Firefox, I am trying to execute a simple command that will scroll the page to the bottom. Here is the command: window.scrollBy(0,3000); Seems straightforward, right? When testing on certain websites like Yahoo.com ...

The JQuery/Ajax script only loads once in the HTML document

I'm currently working on a webpage that displays data from two databases almost instantaneously. However, I've encountered an issue where my JQuery Ajax call only updates the HTML content once. HTML Code: <div class="database"> ...

Correcting the reference to "/" (root) for assets after relocating the site to a subdirectory

I currently have a website located in the public_html directory, where all assets (images, css, js, etc) are referenced using /asset_folder/asset. The "/" at the beginning ensures that the browser starts from the root and navigates through the directories. ...

Selecting elements by their name using vanilla JavaScript

I am facing an issue where I have to assign a value to a checkbox based on certain variables. The challenge lies in the naming convention used in the HTML I am working with: <input id="jc_1" type="checkbox" name="jc[1]"> <input id="jc_2" type="c ...

"Utilizing jQuery to add new items to a list using the

I'm a bit confused about the distinctions among these four lines of code: $('<li>').addClass('restaurant').appendTo('ul'); $('li').addClass('restaurant').appendTo('ul'); $('li& ...

Show off beautiful text using a styled pre component in a React application

I've been attempting to highlight specific text within a React pre element, but unfortunately, it doesn't seem to be working as expected. Instead of displaying the highlighted text, it shows [object Object]. const Text = styled.pre ` col ...

Tips for integrating Tornado authentication with AngularJS

I have been experimenting with the authentication system outlined in the tornado documentation, and I am encountering a Cross-Origin Request issue when trying to integrate it with AngularJS. Is there a way to successfully combine Tornado's authentica ...

Utilizing the Power of GrapesJs in Vue3

Recently, I attempted to integrate the GrapesJS editor into my Vue.js project, but encountered some difficulties. The editor was not visible in the browser, and the designated tag for the editor appeared empty. Here is my editor configuration: <template ...

The MaterialUI Datagrid is throwing an error message for an Invalid Hook Call

Having a strange issue with my simple component. I've imported DataGrid from MaterialUI, defined variables for columns and rows, and rendered the DataGrid in a functional component. However, I'm getting an "invalid hook call" error. Most solution ...

The dropdown menu is malfunctioning when accessed within the mobile view of a jQuery

Take a look at this code snippet on Fiddle: https://jsfiddle.net/rizwanali98601/ngofhc24/12/. The table below contains a dropdown inside a jQuery Datatable. When the button is clicked, an option is supposed to be added to the dropdown. However, in mobile ...

Can config values be dynamically set from an Excel file in Protractor?

I am currently working on parameterizing capabilities using an Excel sheet. For this task, I am utilizing the npm exceljs package for both reading and writing data. Below is a snippet of the code that demonstrates how I am trying to achieve this: //This f ...

{"success":true} however, fineuploader displays an error

{"success":true} is returned by the php server script, indicating successful file upload but fineuploader displays an error message in red on the webpage. Upon checking the console, the following error was found: fineuploader-3.2.min.js: [FineUp ...

What is the destination for next() in Express js?

I'm new to javascript, nodejs, and express, and facing confusion with the usage of next(). I am trying to make my code progress to the next router using next(), but it seems to be moving to the next then instead. This is what my code looks like: // ...

Receiving and monitoring events triggered by a Vue component that was dynamically mounted

I am currently mounting a Vue component dynamically within a mixin to incorporate the resulting HTML into a map popup. While everything is functioning correctly, I am facing an issue with listening to events emitted by the component. I am unsure of how to ...

convert a JSON object to an array using jQuery

Can anyone help me with converting an object into an array using jQuery? [["20"],["30"],["45"],["54"],["33"],["15"],["54"],["41"]] I am looking to achieve an array output like this: [20,30,45,54,33,15,54,41] Any suggestions on how to accomplish this? ...

Customizing response headers in vanilla Node.js

My Node.js setup involves the following flow: Client --> Node.js --> External Rest API The reverse response flow is required. To meet this requirement, I am tasked with capturing response headers from the External Rest API and appending them to Nod ...

Implementing non-blocking asynchronous object return in a node.js function

Struggling with a function that accesses data from a JSON file and queries it for a specific key. Unfortunately, the return function seems to be executing before the query can find the key. Even after querying and attempting to return the variable queryre ...