简体   繁体   中英

Javascript extract unknown number in string

I have a string ctl00_ContentPlaceHolder1_lstViewFormulas_ctrl06_lblCountDown that will come into a javascript function using sender from my asp.net button control...

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

function test(sender) {

}

The need to get the number directly following ctrl, In the example above it would be 06 (ctrl06_lblCountDown)

How can I extract this number using javascript?

Thanks

var str = "ctl00_ContentPlaceHolder1_lstViewFormulas_ctrl06_lblCountDown",
    result = str.match(/.*ctrl(\d+).*/)[1];

Working example: http://jsfiddle.net/RXGb2/

You can extract is using regex easily:

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

Safer way:

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

You could try something like this:

var str = 'ctrl06_lblCountDown',
    numericArray = [],
    numericString,
    num,
    i=0,
    len = 0;


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

len = numericArray.length;

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

}

num = parseInt(numericString,10);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM