-1

I have a string in javascript:

ECTS: 7.5 pts

From this string I need to extract 7.5 and parse it to a float value..

I've tried searching, but none of the solutions I found did the trick. I've tried:

var regex = /^\d+\.\d{0,3}$/;
var string = "ECTS: 7.5 pts";
var number = parseFloat(string.match(regex));
console.log("number is: " + number);

I've tried with a couple of different regular expressions, but none of them have done the trick.

I've created this fiddle to illustrate the problem.

EDIT1

I used to have this /\d+/ as my regex, but that didn't include floating point numbers.

EDIT2

I ended up using this as my regex /[+-]?\d+(\.\d+)?/g

Updated fiddle

Community
  • 1
  • 1
Zeliax
  • 4,987
  • 10
  • 51
  • 79

2 Answers2

2

This works nicely, no need for regex:

var s = "ECTS: 7.5 pts";
var n = parseFloat(s.split(" ")[1]);
$("#test").text(n);
Rob
  • 11,492
  • 14
  • 59
  • 94
  • Nice solution, but I could run into problems with this one as I got a lot of these kinds of strings, and they are not all the same when it comes to spacings. Of course you couldn't know that. +1'ed your solution. – Zeliax May 13 '16 at 08:31
1

did you try this? var digits = Number((/(\d+\.\d+)/.exec('ECTS: 7.5 pts') || []).pop());

Hitmands
  • 13,491
  • 4
  • 34
  • 69