0

i have this kind of string:

COMC1.20DI

I need to extract, in this case "1.20", but number can have decimals or not. How can I do it? I also need to get the start and end position of the number.

For starting position, I found

value.search(/\d/);

But I can't get any code to work for getting the last position of the number.

How can I do this?

Kijewski
  • 25,517
  • 12
  • 101
  • 143
Alan Daitch
  • 79
  • 2
  • 12

5 Answers5

5

This worked for me when I tried:

var value = 'COMC120DI';
alert(value.match(/[\d\.]+/g)[0]);    

This returned "120". If you have multiple numbers in your string, it will only return the first. Not sure if that's what you want. Also, if you have multiple decimal places, it'll return those, too.

Daniel Kaplan
  • 62,768
  • 50
  • 234
  • 356
1

This is how I extracted numbers (with decimal and colon) from a string, which will return numbers as an array.

In my case, it had undefined values in the result array so I removed it by using the filter function.

let numArr = str.match(/[\d\.\:]+/g).map(value => { if (value !='.' && value !=':'){ return value } })
    numArr = numArr.filter(function( element ) {
        return element !== undefined;
});
Stone
  • 583
  • 6
  • 8
-1

For extraction u can use this RegEx:

^(?<START>.*?)(?<NUMBER>[0-9]{1,}((\.|,)?[0-9]{1,})?)(?<END>.*?)$

The group "START" will hold everything before the number, "NUMBER" will hold any number (1| 1,00| 1.0) and finally "END" will hold the rest of the string (behind the number). After u got this 3 pieces u can calculate the start and end position.

k1ll3r8e
  • 729
  • 16
  • 22
-1

You could try this snippet.

var match = text.match(/\d+(?:\.\d+)?/);
if (match) {
    var result = 'Found ' + match[0] + ' on position ' + match.index + ' to ' + (match.index + match[0].length));
}

Note that the regex I'm using is \d+(?:\.\d+)?. It means it won't mistakenly check for other number-and-period format (i.e., "2.3.1", ".123", or "5.") and will only match integers or decimals (which is \d+ with optional \.\d+.

Check it out on JSFiddle.

-1
   var decimal="sdfdfddff34561.20dfgadf234";

   var decimalStart=decimal.slice(decimal.search(/(\d+)/));
   var decimalEnd=decimalStart.search(/[^.0-9]/);
   var ExtractedNumber= decimalStart.slice(0,decimalEnd);

   console.log(ExtractedNumber);

shows this in console: 34561.20

ORParga
  • 392
  • 2
  • 7