我已收到此短信:3,142 people
。我需要从中删除people
并仅获取数字,同时删除逗号。我需要它来处理任何更高的数字,如13,142
或甚至130,142
(每3位数字会得到一个新的逗号)。
因此,简而言之,我只需要获取数字字符,不使用逗号和people
。例如:3,142 people
- > 3142
。
我的第一个版本没有用:
var str2 = "3,142 people";
var patt2 = /\d+/g;
var result2 = str2.match(patt2);
但在我将patt2
更改为/\d+[,]\d+/g
之后,它才有用。
答案 0 :(得分:2)
'3,142 people'.replace(/[^\d]/g, ''); // 3142
JSFiddle演示:http://jsfiddle.net/zjx2hn1f/1/
解释
[] // match any character in this set
[^] // match anything NOT in character set
\d // match only digit
[^\d] // match any character that is NOT a digit
string.replace(/[^\d]/g, '') // replace any character that is NOT a digit with an empty string, in other words, remove it.
答案 1 :(得分:0)
你可以用这个:
var test = '3,142 people';
test.replace(/[^0-9.]/g, "");
它将删除除数字和小数点以外的所有内容