Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我需要从字符串中提取数字
<p id="example">etc etc(5)</p> <p id="example2">etc etc(-5)</p>
我正在使用此代码
alert($("#example").text().match(/\((\d+)\)/)[1]);
如果数字是正数,它可以正常工作,但在负数的情况下会出错
Uncaught TypeError: Cannot read property '1' of null
请帮助我,谢谢
试试这个:
.match(/\((-?\d+)\)/)[1]
-?说“可选减号”。
-?
alert($("#example").text().match(/\((-?\d+)\)/)[1]);
这也将捕获负数。