在 JavaScript 中,如何从以字母开头的字符串(例如“test[123]”)中解析 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>
您可以使用正则表达式来匹配数字:
$(this).attr("id").match(/\d+/)
parseInt(input.replace(/[^0-9-]/,""),10)
可能只是用 .replace() 过滤掉字符串。如果还有其他方法那么我不知道:
parseInt("attribute[123]".replace("attribute[", "").replace("]", "")));
您可能可以使用一些正则表达式将其仅放入一个 .replace() 中,但我不擅长正则表达式,所以我只做了两次。
在浏览器中使用
进行测试javascript:alert(parseInt("attribute[123]".replace("attribute[", "").replace("]", "")));
应报警123。