Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I replace a character in a string with regex and javascript?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading