Count the number of integers in a string

后端 未结 4 2066
不思量自难忘°
不思量自难忘° 2020-11-29 09:15

how can I count the number of integers in a string using jQuery or javascript?

For example g66ghy7 = 3

相关标签:
4条回答
  • 2020-11-29 09:30

    I find this to look pretty/simple:

    var count = ('1a2b3c'.match(/\d/g) || []).length
    

    A RegExp will probably perform better (it appears):

    var r = new RegExp('\\d', 'g')
      , count = 0
    
    while(r.exec('1a2b3c')) count++;
    
    0 讨论(0)
  • 2020-11-29 09:43

    The simplest solution would be to use a regular expression to replace all but the numeric values and pull out the length afterwards. Consider the following:

    var s = 'g66ghy7'; 
    alert(s.replace(/\D/g, '').length); //3
    
    0 讨论(0)
  • 2020-11-29 09:45
    alert("g66ghy7".replace(/[^0-9]/g,"").length);
    

    Look here.

    0 讨论(0)
  • 2020-11-29 09:54

    A little longer alternative is to convert each char to a number; if it doesn't fail, raise the counter.

    var sTest = "g66ghy7";
    
    var iCount = 0;
    for (iIndex in sTest) {
        if (!isNaN(parseInt(sTest[iIndex]))) {
            iCount++;
        }
    }
    alert(iCount);
    

    Also see my jsfiddle.

    0 讨论(0)
提交回复
热议问题