-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

2
  • 2
    stackoverflow.com/questions/17374893/… Commented May 13, 2016 at 8:22
  • @WiktorStribiżew I did check out this one already, and it didn't work. I tried it again and it did. Thanks.. Commented May 13, 2016 at 8:26

2 Answers 2

2

This works nicely, no need for regex:

var s = "ECTS: 7.5 pts";
var n = parseFloat(s.split(" ")[1]);
$("#test").text(n);
Sign up to request clarification or add additional context in comments.

1 Comment

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

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.