在 JavaScript 中从字符串解析 Int

问题描述 投票:0回答:3

在 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>
javascript jquery
3个回答
58
投票

您可以使用正则表达式来匹配数字:

$(this).attr("id").match(/\d+/)

25
投票
parseInt(input.replace(/[^0-9-]/,""),10)

1
投票

可能只是用 .replace() 过滤掉字符串。如果还有其他方法那么我不知道:

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

您可能可以使用一些正则表达式将其仅放入一个 .replace() 中,但我不擅长正则表达式,所以我只做了两次。

在浏览器中使用

进行测试
javascript:alert(parseInt("attribute[123]".replace("attribute[", "").replace("]", "")));

应报警123。

© www.soinside.com 2019 - 2024. All rights reserved.