Javascript RegEx数字仅来自后面带有逗号和文本的数字

Javascript RegEx number only from number with comma and text after

本文关键字:数字 文本 RegEx Javascript      更新时间:2023-09-26

我有一个文本: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之后,它起了作用。

您可以使用这个:

var test = '3,142 people';
test.replace(/[^0-9.]/g, "");

它将删除除数字和小数点之外的所有内容

'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.