I have a string:
let y = ".1875 X 7.00 X 8.800";
I would like to return this as an array of 3 numbers: 0.1875, 7.00, 8.800
I need to convert .1875 into 0.1875, however you can’t just target the first character because what if the string is like so:
let x = "7.00 X .1875 X 8.800";
or another difficult example
let y = ".50" x 1.25" x 7.125" will make one part"
This is my attempt so far:
let numbers = x.match(/(\d*\.)?\d+/g)
numbers.map(n => parseFloat(n))
var thickness = numbers[0]
var width = numbers[1]
var length = numbers[2]
if(thickness.charAt(0) == '.'){
let stringA = numbers[0].match(/^(\.)/g)
let stringB = "0"
thickness.replace(stringA, stringB)
console.log(thickness)}
else {
alert('failure');
}
I can’t seem to replace the . in .1875 to 0.1875, any help much appreciated!
>Solution :
Here is one way to do so using regex:
let x = "7.00 X .1875 X 8.800";
const pattern = /\d*\.?\d+/g;
const numbers = [...x.matchAll(pattern)].map(Number);
console.log(numbers);
\d*: Matches any digit between 0 and unlimited times, as much as possible.\.?: Optionally matches..\d+: Matches any digit between 1 and unlimited times, as much as possible.