0

I would like to get a numeric value in a string which is in the format 1 111.

I used a regex to extract it: ([0-9]*)\s([0-9]*)

then I thought that I will obtain the correct result with this operation: regex_result[1]*1000+regex_result[2]

But actually I just have to addition them and I do not understand why.

var str= "Bit rate                                 : 5 333 kb/s"

var bitrate= str.match(/Bit\srate\s*:\s([0-9]*)\s([0-9]*)\s/);
console.log(bitrate);

//attempted result, but incorrect code
console.log(bitrate[1]+bitrate[2]);

//attempted correct code, but wrong result
console.log(bitrate[1]*1000+bitrate[2]);
DrCord
  • 3,917
  • 3
  • 34
  • 47
Gaël Barbin
  • 3,769
  • 3
  • 25
  • 52

2 Answers2

-1

Here, the second captured group just so happens to be 3 characters long, so multiplying the first captured group by 1000 and adding it to the second group will just so happen to produce the same result as plain concatenation.

But you have to add them together properly first. Your second attempt isn't working properly because the right-hand side of the + is a string, and a number + a string results in concatenation, not addition:

var str = "Bit rate                                 : 5 333 kb/s"

var bitrate = str.match(/Bit\srate\s*:\s([0-9]*)\s([0-9]*)\s/);
console.log(bitrate[1] * 1000 + Number(bitrate[2]));

If the input isn't guaranteed to have exactly 3 digits in the second capturing group, the concatenation method won't work.

Snow
  • 3,820
  • 3
  • 13
  • 39
-2

You can parse them as ints instead of manipulating strings

var str= "Bit rate                                 : 5 333 kb/s"

var bitrate= str.match(/Bit\srate\s*:\s([0-9]*)\s([0-9]*)\s/);
console.log(bitrate);

console.log(parseInt(bitrate[1] * 1000) + parseInt(bitrate[2]));
chevybow
  • 9,959
  • 6
  • 24
  • 39
  • `parseInt(bitrate[1] * 1000)` the inner expression will already produce a number, no need to parse it. – VLAZ Dec 31 '19 at 19:00