Home > Software design >  How to get "m" meters and "km" from string using regex?
How to get "m" meters and "km" from string using regex?

Time:06-18

I was trying to get integer from below string and convert it again replace it . Need regex pattern to get mtr, km array from string. Little help will be highly appreciated.

let stringText = "Please continue for 290 m. And then take left and continue for 1.2 km.";
console.log(stringText);
let mtr_pattern = "";
let kn_pattern = "";
let numArr = stringText.match(/\d \.\d |\d \b|\d (?=\w)/g) || []);
numArr = numArr.filter(n => n != '.');
console.log("numArry", numArr);

output should be : Please continue for 0.18 miles. And then take left and continue for 0.74 miles

CodePudding user response:

You could take the numerical value and the unit. Then convert the value to miles.

let
    km2miles = km => km * 0.621371,
    string = "Please continue for 290 m. And then take left and continue for 1.2 km.",
    result = string.replace(
        /(\d \.?\d*) (k?m)/g,
        (_, a, b) => km2miles(b === 'km' ? a : a / 1000).toFixed(2)   ' miles'
    );

console.log(string);
console.log(result);

  • Related