Search code examples
javascripttypescriptarray-map

Find integers/floats/strings in a string of text and put in array


I have a string and want split them in an array based on type. I can extract numbers and floats like below, but is not complete to my goal

 var arr = "this is a string 5.86 x10‘9/l 1.90 7.00"
   .match(/\d+\.\d+|\d+\b|\d+(?=\w)/g)
   .map(function (v) {return v;});

 console.log(arr);

 arr = [5.86, 10, 9, 1.9, 7]

I would like have even chunk of string type and mixed like "x10‘9/l":

 arr = ["this is a string", 5.86, "x10‘9/l", 1.9, 7]

can someone figure out?


Solution

  •  const result = [];
    
     const str = "this is a string 5.86 x10‘9/l 1.90 7.00";
    
     result.push(str.split(" ").reduce((acc, part) => isNaN(part) ? acc + " " + part : ((acc && result.push(acc)), result.push(+part), ""), ""));