0
votes

I have this example:

const str = "Icecream, Milk, vanilla syrup, ice cubes20.0 SR180 calories"

I need a way to get the 20.0 from the string, it always positioned before SR

My try is convert the string to array like so:

const strArr = str.split(' ');

and try to get the index of the object contain SR

const index = strArr.map((object) => object).indexOf('SR');

But it showed me a result of -1

I was thinking to get the object by index - 1 to have the result of 20.0

any other short idea to make that done properly

Thanks

2
Regex? str.match(/([\d\.]+) SR/)[1] - Johnny Mopp
/(\d+(\.\d+)?) SR/ - Hassan Imam

2 Answers

0
votes

If you're gonna split do it on SR. Then extract the digits from the end of the first string.

const str = "Icecream, Milk, vanilla syrup, ice cubes20.0 SR180 calories"
var arr = str.split("SR");
var rev = arr[0].trim().split("");
var num = []
while (rev.length) {
  var char = rev.pop();
  if (!(char >= '0' && char <= '9' || char == ".")) {
    break;
  }
  num.push(char);
}
var result = num.reverse().join("");
console.log(result)
0
votes

I think this might help:

const finalNumber = str.split(' SR')[0].split(' ').pop().replace(/[^\d.]/g, '');
console.log(finalNumber);