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?

2
  • Are the decimals, when present, always only to the hundredths? Commented Nov 3, 2014 at 2:03
  • IS the decimal number will always at the center of string? or it could be anywhere? Commented Nov 3, 2014 at 2:03

5 Answers 5

4

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

-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.

Comments

-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.

Comments

-2
   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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.