2009-01-15 119 views
21

在JavaScript中,从以字母开头的字符串(如“test [123]”)解析INT的最佳方法是什么?我需要一些可以用于下面例子的东西。从javascript中的字符串解析Int

我的JS:

$(document).ready(function() { 

    $(':input').change(function() { 
     id = parseInt($(this).attr("id")); //fails for the data below 
     alert(id); 
    }); 
} 

我生成的HTML:

<select id="attribute[123]"> 
<!-- various options --> 
</select> 
<select id="attribute[456]"> 
<!-- various options --> 
</select> 

谢谢!

回答

57

你可以使用正则表达式匹配的数量:

$(this).attr("id").match(/\d+/) 
23
parseInt(input.replace(/[^0-9-]/,""),10) 
+0

有趣的是,如果有这将无法工作像“1e10”这样的有效float文字 – Triptych 2009-01-16 00:22:28

+1

如果没有全局标志,我认为这完全不起作用。 – Prestaul 2009-01-16 00:40:38

1

也许只是用.replace()过滤掉字符串。如果有另一种方式则我不知道它:

parseInt("attribute[123]".replace("attribute[", "").replace("]", ""))); 

你也许可以使用一些正则表达式来提出,在只有一个.replace(),但我不擅长用正则表达式,所以我只是做了两次。

测试这在你的浏览器

javascript:alert(parseInt("attribute[123]".replace("attribute[", "").replace("]", ""))); 

应提醒123