当在字符串中找到 6 个或更多数字时,我试图从字符串中删除数字。
我不想删除字符串中的所有 数字,只删除第 6 位及之后的任何数字。前5个需要保留。
例如:
var val = 'Hello, this is my text. I was born in 1984, and currently my age is 29 years';
if (val.match(/[0-9]/g, '').length > 5) {
// strip any digits beyond the 5th
}
在 if 中的任何内容之后,val 现在应该包含:
var val = 'Hello, this is my text. I was born in 1984, and currently my age is 2 years';
我觉得我可能忽略了一些非常容易的事情。然而,我在网络上的搜索似乎一无所获。
最佳答案
var val = 'Hello, this is my text. I was born in 1984, and currently my age is 29 years';
var count = 0;
var str = val.replace(/\d/g, function(match){ return (++count<6) ? match : ""; });
console.log(str);
关于javascript - 是否可以使用正则表达式去除字符串中超过 X 位的数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23341794/