'Extract number with decimals in string (Javascript)

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?



Solution 1:[1]

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.

Solution 2:[2]

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;
});

Solution 3:[3]

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.

Solution 4:[4]

   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

Solution 5:[5]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Daniel Kaplan
Solution 2 Stone
Solution 3
Solution 4 ORParga
Solution 5