Javascript Regular Expressions - Replace non-numeric characters

前端 未结 10 941
清歌不尽
清歌不尽 2021-01-30 12:32

This works:

var.replace(/[^0-9]+/g, \'\');  

That simple snippet will replace anything that is not a number with nothing.

But decimals

相关标签:
10条回答
  • 2021-01-30 13:09

    Did you escape the period? var.replace(/[^0-9\.]+/g, '');

    0 讨论(0)
  • 2021-01-30 13:11

    Replacing something that is not a number is a little trickier than replacing something that is a number.

    Those suggesting to simply add the dot, are ignoring the fact that . is also used as a period, so:

    This is a test. 0.9, 1, 2, 3 will become .0.9123.

    The specific regex in your problem will depend a lot on the purpose. If you only have a single number in your string, you could do this:

    var.replace(/.*?(([0-9]*\.)?[0-9]+).*/g, "$1")

    This finds the first number, and replaces the entire string with the matched number.

    0 讨论(0)
  • 2021-01-30 13:11

    If you don't want to catch IP address along with decimals:

    var.replace(/[^0-9]+\\.?[0-9]*/g, '');
    

    Which will only catch numerals with one or zero periods

    0 讨论(0)
  • 2021-01-30 13:15

    How about doing this:

    var numbers = str.gsub(/[0-9]*\.?[0-9]+/, "#{0} ");
    
    0 讨论(0)
提交回复
热议问题