Searching in Javascript: Extracting an "ID" from a given string using regular expressions

I am trying to work with the following string: comment_1234

My goal is to extract the number 1234 from this string. How can I achieve this?

Update: Despite attempting various solutions provided, none seem to be working for me. Could there be an issue with my code? The alert function does not trigger as expected:

var nameValue = dojo.query('#Comments .Comment:last-child > a[name]').attr('name');
alert('name value: ' + nameValue); // comment_1234
var commentId = nameValue.split("_")[1];
// var commentId = nameValue.match(/\d+/)[0];
// var commentId = nameValue.match(/^comment_(\d+)/)[1];
alert('comment id: ' + commentId); //never gets called. Why?

Solution:

After some investigation, I identified the root of my issue...the variable nameValue appeared to be a string but was actually something else. By explicitly casting nameValue as a string, I was able to resolve the problem.

var nameValue = dojo.query('#Comments .Comment:last-child > a[name]').attr('name'); //comment_1234
var string = String(nameValue); //cast nameValue as a string
var id = string.match(/^comment_(\d+)/)[1]; //1234

Answer №1

Using a regex to extract numbers from a string: someString.match(/\d+/)[0]; // 1234

To target digits after "comment_":

Extracting numbers specifically following "comment_": someString.match(/^comment_(\d+)/)[1]; // 1234

Answer №2

function GetNumberFromStr(str) {
    var parts = str.split('_');
    return parts[parts.length - 1];
}

var number = GetNumberFromStr('text_5678');

Answer №3

let wishId = "WishID=1List"
let result = wishId.match(/WishID=(.*)List/);
alert (result[1]);

if(result[1]==""){
  alert('Empty');
}

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

The Salvattore grid became unresponsive and malfunctioned as soon as AngularJS was integrated

After incorporating AngularJS into my project, Salvatore grid suddenly ceased to function and stopped rendering properly. I am interested in utilizing the ng-repeat feature to iterate through all items and showcase them within the Salvatore grid layout. ...

The bundle.js file encountered an issue while running UglifyJs, expecting a name

I have been attempting to utilize UglifyJS to compress/minimize my bundle.js file. However, when executing webpack -p, I encountered the following error message: ERROR in bundle.js from UglifyJs Name expected [bundle.js:105519,6] The line causing the iss ...

Tips for utilizing express in your typescript projects

I'm curious about the transition of definition files from tsd to typings, and now to @types. How can I incorporate @types in a node/express project? What is currently preferred and what's the reason for moving from tsd to typing and finally to @t ...

Images stored locally are not appearing in React JS applications

I'm currently exploring React JS and Material UI to develop a dynamic web application. I'm attempting to link a local image using 'url(${process.env.PUBLIC_URL})' but unfortunately, the image is not showing up for some unknown reason. ...

A specialized identifier for nested objects in a React component

I am currently working with a JSON data structure that looks like this: [ [ { city: x patients: x id: 1 }, { city: y patients: y id: 2 } ], [ { city: x patients: x id: 1 }, { city: y patients: y id: 2 } ...

Search for data in Mongoose by utilizing a query object that has been obtained from a query string

After extracting and parsing a querystring from a URL, I am able to map it into an object structure like this: { '$and': [ { length: { '$gt': '2' } }, { length: { '$lt': '55555' } } ] } This object is st ...

What is the regular expression for extracting paths containing tabs and line breaks?

There is a specific path structure dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext that needs to be processed segment by segment. It is necessary to determine the number of tabs preceding each segment and keep the rest of the pat ...

Out of the box, Next.js is equipped with a standard error message stating: "TypeError: Cannot read properties of null (reading 'useContext')"

After just setting up next.js for my upcoming website, I ran into some unexpected errors while trying to host it with "next". The specific error message I encountered was: TypeError: Cannot read properties of null (reading 'useContext') This iss ...

The implementation of reflux involves creating a shared component, where the data from the final component will overwrite all existing data

Dear friends, I have been facing a problem for a week that I need your help with. I have used React and Reflux to build a common component. I have used props to set different values for each component, but unfortunately, it is not working as expected. T ...

Choose the specific selector following the current selector

Consider this example of code: <script> $(document).ready(function () { $('span').each(function () { $(this).html('<div></div>') ; if ( $(this).attr('id') == 'W0' ...

Angular tutorial: Accessing individual HTML elements within the *ngFor loop

I am facing an issue trying to access the "box-message" class using "document.querySelectorAll('.box-message')" within a tree structure where the "*ngFor" directive is utilized. After making an "http rest" request, the *ngFor directive finishes ...

Tips on changing the default value of a Material UI prop method in React JS

Currently, I'm utilizing React JS and I've brought in a component from Material UI known as (https://material-ui.com/api/table-pagination/). My goal is to customize the Default labelDisplayedRows that looks like this: ({ from, to, count }) => ...

Disable form input fields while keeping all other elements enabled

Currently, I am facing a dilemma where I must deactivate specific input fields within a form. Given that there are numerous fields to consider, individually disabling each one seems impractical. Can anyone offer advice on how to disable a set of elements ...

I'm having trouble grasping the concept of serving gzip-compressed JavaScript and CSS files

Why is it important to serve compressed JavaScript and CSS files? I understand that it reduces file size, but does the browser/webserver have to decompress them to read them? It's been mentioned that the webserver handles the compression. Does this me ...

The combination of Node.js, Monk, PapaParse, Bluebird, and MongoDB seems to be causing issues with updating the database

I'm currently working on a script to extract data from a CSV file and store it in my database. Everything seems to be functioning properly, except for one issue - I can't seem to get the process to end without either erasing data from the databas ...

Difficulty with the increment of my counter when using addeventlistener

I'm currently facing a challenge that I can't seem to figure out... Here is the issue (in JavaScript): export default { name: "TodoList", data() { return { title: "", content: null, isDone: true, count: 0, n ...

Getting JSON data with D3.js: A step-by-step guide

My JSON file is external and has a specific structure: { data: [ { 0: 'cat', 1: 232, 2: 45 }, { 0: 'dog', 1: 21, 2: 9 }, { 0: 'lion', ...

Attempting to incorporate a JavaScript script into my Java Maven project

Currently, I am incorporating an Ajax request into my Java Maven project. This project follows the MVC pattern, with the view being rendered in HTML and the model and controller being implemented in Java. My goal is to retrieve data from a data set contain ...

The locomotive scroll elements mysteriously vanish as you scroll, leaving the footer abruptly cut off

After successfully implementing locomotive scroll on my website, I encountered some issues when uploading it to a live server. Elements started bumping into each other causing flickering and disappearing, with the footer being cut off as well. It appears t ...

Struggling to pinpoint the exact element in Python/Selenium

As I work on creating a website manipulation script to automate the process of email mailbox creation on our hosted provider, I find myself navigating new territory in Python and web scripting. If something seems off or subpar in my script, it's beca ...