是否可以使用正则表达式删除字符串中超过X位的数字?

时间:2014-04-28 12:57:42

标签: javascript regex

我正在尝试从字符串中删除数字,当在字符串中找到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';

我觉得我可能很容易忽略这一点。然而,我在网上的搜索似乎没有产生任何结果。

2 个答案:

答案 0 :(得分:5)

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);

答案 1 :(得分:0)

epascarello以优秀的答案击败了我,无论如何这里都是一个循环解决方案。

function removeDigits(s, n) {
  var c,
      count = 0,
      t = [];

  // if there are less than n digits, return s
  if (s.replace(/\D/g,'').length < n) {
    return s;
  }

  // Copy the string up to the first n digits
  for (var i=0, iLen=s.length; i<iLen && count < n; i++) {
    c = s.charAt(i);

    if (re.test(c)) ++count;

    t.push(c);
  }

  // Return string so far and remove digits from the rest
  return t.join('') + s.substr(i).replace(/\d/g,'');
}