Strip all non-numeric characters from string in JavaScript

后端 未结 10 1479
醉酒成梦
醉酒成梦 2020-11-22 13:44

Consider a non-DOM scenario where you\'d want to remove all non-numeric characters from a string using JavaScript/ECMAScript. Any characters that are in range 0 - 9

相关标签:
10条回答
  • 2020-11-22 14:21

    we are in 2017 now you can also use ES2016

    var a = 'abc123.8<blah>';
    console.log([...a].filter( e => isFinite(e)).join(''));
    

    or

    console.log([...'abc123.8<blah>'].filter( e => isFinite(e)).join(''));  
    

    The result is

    1238
    
    0 讨论(0)
  • 2020-11-22 14:27

    Use a regular expression, if your script implementation supports them. Something like:

    myString.replace(/[^0-9]/g, '');
    
    0 讨论(0)
  • 2020-11-22 14:32

    If you need this to leave the dot for float numbers, use this

    var s = "-12345.50 €".replace(/[^\d.-]/g, ''); // gives "-12345.50"
    
    0 讨论(0)
  • 2020-11-22 14:35

    In Angular / Ionic / VueJS -- I just came up with a simple method of:

    stripNaN(txt: any) {
        return txt.toString().replace(/[^a-zA-Z0-9]/g, "");
    }
    

    Usage on the view:

    <a [href]="'tel:'+stripNaN(single.meta['phone'])" [innerHTML]="stripNaN(single.meta['phone'])"></a>
    
    0 讨论(0)
提交回复
热议问题