-7

the regular express /\D/g identifies all non numeric characters and the following code will replace the letter 'q' and decimal '.' in str and result in 10025

  var str = "10q0.25"; 
  var result = str.replace(/\D/g, '');

How can the regex be changed so as to allow the decimal point also and resulting in 100.25 ?

Lakshman Pilaka
  • 1,556
  • 2
  • 22
  • 41

1 Answers1

2

Your solution is almost correct, but it will remove all non-numeric characters. My regex consists of a group or characters, which should remain in string, [ ] is a group of characters to match, [^ ] means group of characters not to match (inverted match), so [^0-9.] means that you want to replace every character except 0 through 9 and . (0-9) with an empty string ''

var str = "10q0.25"; 
var result = str.replace(/[^0-9.]/g, '');

console.log(result)
Code Maniac
  • 35,187
  • 4
  • 31
  • 54
Dominik Matis
  • 2,009
  • 8
  • 15