namzaG
namzaG

Reputation: 582

regex (only 1 dot)

I have a regEx where I replace everything whats not a number:

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

how can i make sure it will only allow 1 dot
(the second dot will be replaced like the others)

(I know you can use input just number (thats not an option in this project for me))

Upvotes: 0

Views: 734

Answers (2)

namzaG
namzaG

Reputation: 582

I resolved it with.

this.value = this.value.replace(/.*?(\d+.\d+).*/g, "$1");

Upvotes: -1

Terry
Terry

Reputation: 66228

You can use a simple trick of:

  1. splitting a string by ., and then only joining the first two elements of the array (using .splice(0,2)) with a . and the rest with nothing
  2. using a simple regex pattern to replace all non-digit and non-period characters: /[^\d\.]/gi

Here is an example code:

// Assuming that `yourString` is the input you want to parse
// Step 1: Split and rejoin, keeping only first occurence of `.`
var splitStr = yourString.split('.');
var parsedStr = splitStr[0];
if (splitStr.length) {
    parsedStr = splitStr.splice(0, 2).join('.') + splitStr.join('');
}

// Step 2: Remove all non-numeric characters
parsedStr = parsedStr.replace(/[^\d\.]/gi, '');

Proof-of-concept example:

var tests = [
  'xx99',
  '99xx',
  'xx99xx',
  'xxxx999.99.9xxx',
  'xxxx 999.99.9 xxx',
  'xx99xx.xx99xx.x9',
  'xx99xx.99x.9x',
  'xx99.xx99.9xx'
];

for (var i = 0; i < tests.length; i++) {
  var str = tests[i];

  // Split and rejoin, keeping only first occurence of `.`
  var splitStr = str.split('.');
  var parsedStr = splitStr[0];
  if (splitStr.length) {
    parsedStr = splitStr.splice(0, 2).join('.') + splitStr.join('');
  }
  
  // Remove all non-numeric characters
  parsedStr = parsedStr.replace(/[^\d\.]/gi, '');
  console.log('Original: ' + str + '\nParsed: ' + parsedStr);
}

Upvotes: 4

Related Questions