Strip all non-numeric characters from string in JavaScript

后端 未结 10 1478
醉酒成梦
醉酒成梦 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:10

    Short function to remove all non-numeric characters but keep the decimal (and return the number):

    parseNum = str => +str.replace(/[^.\d]/g, '');
    let str = 'a1b2c.d3e';
    console.log(parseNum(str));

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

    Unfortunately none of the answers above worked for me.

    I was looking to convert currency numbers from strings like $123,232,122.11 (1232332122.11) or USD 123,122.892 (123122.892) or any currency like ₹ 98,79,112.50 (9879112.5) to give me a number output including the decimal pointer.

    Had to make my own regex which looks something like this:

    str = str.match(/\d|\./g).join('');
    
    0 讨论(0)
  • 2020-11-22 14:13

    Something along the lines of:

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

    You can use a RegExp to replace all the non-digit characters:

    var myString = 'abc123.8<blah>';
    myString = myString.replace(/[^\d]/g, ''); // 1238
    
    0 讨论(0)
  • 2020-11-22 14:20

    Use the string's .replace method with a regex of \D, which is a shorthand character class that matches all non-digits:

    myString = myString.replace(/\D/g,'');
    
    0 讨论(0)
  • 2020-11-22 14:20

    try

    myString.match(/\d/g).join``
    

    var myString = 'abc123.8<blah>'
    console.log( myString.match(/\d/g).join`` );

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