How to retrieve a variable number from a JavaScript string

In an ASP.NET environment, I am working with a string called ctl00_ContentPlaceHolder1_lstViewFormulas_ctrl06_lblCountDown, which will be passed into a JavaScript function using the sender parameter from my button control...

<asp:Button ID="buttStartTimer" runat="server" CausesValidation="false" OnClientClick="javascript:countdown(this);" Text="Start" />

Here is the JavaScript function:

function test(sender) {

}

I need to extract the number that directly follows "ctrl" in the string. For example, in the above scenario, the number would be 06 (ctrl06_lblCountDown)

Is there a way to achieve this extraction using JavaScript?

Thank you

Answer №1

let text = "ctl00_ContentPlaceHolder1_lstViewFormulas_ctrl06_lblCountDown",
    findNumber = text.match(/.*ctrl(\d+).*/)[1];

Example in action: http://jsfiddle.net/RXGb2/

Answer №2

If you need to retrieve a number from a string, using regex can make the process quick and easy:

var text = "ctl00_ContentPlaceHolder1_lstViewFormulas_ctrl06_lblCountDown";
var number = parseInt(text.match(/_ctrl([\d]*)_/)[1], 10);

For a more cautious approach:

var text = "ctl00_ContentPlaceHolder1_lstViewFormulas_ctrl06_lblCountDown";
var parts = text.match(/_ctrl([\d]*)_/), number;
if(parts.length > 1) {
    number = parseInt(parts[1], 10);
}

Answer №3

Here is a possible solution you can use:

let string = 'ctrl06_lblCountDown',
    numericArray = [],
    numericString,
    number,
    i = 0,
    length = 0;

numericArray = string.match(/[0-9]/g);

length = numericArray.length;

numericString = '';
for(i = 0; i < length; i++){
    numericString += numericArray[i];
}

number = parseInt(numericString, 10);

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

Why isn't the hover function working on the table row element?

When I try to apply a hover effect on tbody and td elements, it works perfectly. However, when I apply the same effect to the tr element, it doesn't work as expected. I am using inline style (js pattern) rather than CSS code and incorporating Radium i ...

Clicking on the user will reveal a modal containing all of the user's detailed information

**I am trying to pass the correct user data to the modal ViewUser component, but it keeps displaying the same user regardless of which user I click on. How can I specify the specific user whose data should be shown? I am sending the user information as a ...

Effortlessly Concealing Numerous Elements with a Single Click in Pure JavaScript

I have successfully created an HTML accordion, but I am facing an issue. I want to implement a functionality where clicking on one accordion button will expand its content while hiding all other accordion contents. For example, if I click on accordion one ...

In JavaScript, using window["functionName"](arguments) will result in a TypeError message saying that the function does not exist

When trying to execute an AJAX function based on the active tab in my application, everything works smoothly when I trigger the function after specific events. However, I encounter difficulties when attempting to call the function using a dynamically gener ...

Create a JavaScript variable every few seconds and generate a JSON array of the variable whenever it is updated

My variable, which consists of random numbers generated by mathrandom every second, such as "14323121", needs to be saved to an array for the latest 10 updates. function EveryOneSec() { var numbers = Math.random(); // I want to create an array from th ...

Distinguishing Response Headers in XMLHttpRequest and jQuery AJAX FunctionUniqueness:

Hello, I'm facing an issue that is not a duplicate. Here is the code snippet: var data = {'userId': window.cookie.get('userId'), 'sessionId': window.cookie.get('sessionId')} $.post(window.DbUrl + '/t ...

Switching Profiles in XPages

In my Xpages project, I have two different user profiles set up. I am currently attempting to develop a function that would allow me to easily switch between these two profiles. However, I am unsure of the steps needed to accomplish this task. ...

Error message: The variable datepicker_instActive is not defined within Jquery-ui Datepicker

Having trouble with a Rails + Angular app where I've implemented the jquery-ui datepicker. The console is showing an error that says: TypeError: datepicker_instActive is undefined if(!$.datepicker._isDisabledDatepicker( datepicker_instActive.inline? ...

Encountered an error in the React.js app where it cannot read the property 'Tag' of undefined from domhandler

I recently encountered an issue with my react.js project, which utilizes domhandler v4.2.0 through cheerio. Everything was running smoothly for months until one day, I started getting this error during the build process: domelementtype package includes a ...

Inheritance of Mongoose methods across all Schemas using the Schema method

Currently, I am working on nodejs with Mongoose and have data in various collections with _id as a string manually written by the user. I am looking to refactor this process and automate the generation of _id. My aim is to create a separate JavaScript fil ...

Issues with babel plugin-proposal-decorators failing to meet expectations

I recently included these two devDependencies in my package.json: "@babel/plugin-proposal-class-properties": "^7.1.0", "@babel/plugin-proposal-decorators": "^7.1.6", In the configuration file .babelrc, I have listed them as plugins: { "presets": ["m ...

Determining the aspect ratio of an image

When trying to append an image to a div, I use the following code segment: $thisComp.find('.DummyImage').attr("src", this.imageUrl); Following this, I make an ajax call to retrieve the aspect ratio of the image: $.ajax(this.imageUrl).done( ...

Is there a way to access a Word document directly without needing to save it on the server first?

Currently, I am creating customized word documents from a template for users by using merge fields. For instance, replacing "User's name" with the actual user's name. Presently, I save these documents on the server using the following code: obje ...

Creating metadata for a node/npm module build

Looking for a solution to output JSON with build date and updated minor version number using grunt and requirejs for our application. It seems like this would be a common requirement. Any existing tools that can achieve this? ...

Tips for creating a conditional confirm dialog box in Asp.net using JQuery/Javascript

I have some jQuery and traditional JavaScript mixed together to validate a textbox on my ASP sample page. There is a button, a textbox, and a button_click event in the code behind. When the button is clicked, I want to show an alert if the textbox is empty ...

Leveraging Parse methods within a Node JS Cron job

My current task involves writing a Cron Job that requires the use of Parse methods. I have the following code snippet at hand: var crontab = require('node-crontab'); var jobId = crontab.scheduleJob("* * * * * *", function(){ ...

Avoid executing top-level path middleware with app.use('/') in Express routing when directly accessing child or nested paths

Perhaps the title may not be as accurate as I hoped, but I have a very simple example to share. On my website, there are two main areas - a public area and a restricted admin area. example.com/admin (admin home page) example.com/admin/news (news page) ...

The VueRouter is unresponsive and not functioning as expected

I have been delving into Vue. Through the npm install vue-router command, I added vue-router to my project. Subsequently, I incorporated VueRouter and defined my URL paths within the VueRouter instances located in the main.js file. I created an About compo ...

What is holding Firestore back from advancing while Firebase Realtime Database continues to evolve?

I am currently working on a chat application using Firebase within my Vue.js project. In this setup, I need to display the user's status as either active or inactive. To achieve this, I implemented the solution provided by Firebase at https://firebase ...

Regain focus after selecting a date with Bootstrap datepicker

When initializing a bootstrap datepicker from eternicode with the parameter autoclose: true, there are two undesired behaviors that occur: After closing the picker, tabbing into the next field causes you to start at the beginning of the document again, w ...