Javascript提取字符串中的未知数字

时间:2013-01-24 17:04:17

标签: javascript asp.net regex

我有一个字符串ctl00_ContentPlaceHolder1_lstViewFormulas_ctrl06_lblCountDown,它将使用我的asp.net按钮控件中的发送器进入javascript函数...

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

功能测试(发件人){

}

需要在ctrl之后直接获取数字,在上面的示例中它将是06(ctrl06_lblCountDown)

如何使用javascript提取此数字?

由于

3 个答案:

答案 0 :(得分:1)

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

工作示例:http://jsfiddle.net/RXGb2/

答案 1 :(得分:0)

您可以轻松提取使用正则表达式:

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

更安全的方式:

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

答案 2 :(得分:0)

您可以尝试这样的事情:

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);