-5

For example we have next string in javaScript

var str = "abc,de 55,5gggggg,hhhhhh 666 "

How i can get 55,5 as number?

ivan
  • 31
  • 6
  • Define the format of you numbers. – Oriol Aug 10 '16 at 18:07
  • 1
    This can be done using regex and the match method. On mobile now so can't give you specifics but it should point you in the right direction. Possible regex: /([0-9,]+)/ – Maarten Bicknese Aug 10 '16 at 18:07
  • Can you please explain your case a little bit more? What should return in the case of "55,5 abc 44,5"? I would advise looking into regular expressions and capture groups after you've refined your requirements http://www.regular-expressions.info/brackets.html – Hodrobond Aug 10 '16 at 18:07
  • 2
    Possible duplicate of [how to extract decimal number from string using javascript](http://stackoverflow.com/questions/10411833/how-to-extract-decimal-number-from-string-using-javascript) – Test Aug 10 '16 at 18:09

3 Answers3

3

It depends on what you can assume about your number, but for the example and a lot of cases this should work:

var str = "abc,de 55,5gggggg,hhhhhh";
var match = /\d+(,\d+)?/.exec(str);
var number;
if (match) {
  number = Number(match[0].replace(',', '.'));
  console.log(number);
} else console.log("didnt find anything.");
ASDFGerte
  • 4,695
  • 6
  • 16
  • 33
0

var str = "abc,de 55,5gggggg,hhhhhh"

var intRegex = /\d+((.|,)\d+)?/
var number = str.match(intRegex);
console.log(number[0]);
CasualBot
  • 86
  • 5
0

JS fiddle:

https://jsfiddle.net/jiteshsojitra/5vk1mxxw/

var str = "abc,de 55,5gggggg,hhhhhh"
str = str.replace(/([a-zA-Z ])/g, "").replace(/,\s*$/, "");
if (str.match(/,/g).length > 1) // if there's more than one comma
    str = str.replace(',', '');
alert (str);
Jitesh Sojitra
  • 3,655
  • 7
  • 27
  • 46