2009-01-15 151 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