Home > Mobile >  How to replace a character within a string with regex?
How to replace a character within a string with regex?

Time:03-23

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!

CodePudding user response:

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.

CodePudding user response:

"I would like to return this as an array of 3 numbers: 0.1875, 7.00, 8.800"

The three numbers are equal to and represented as 0.1875, 7 and 8.8.

Split the string and parse the numbers:

let y = ".1875 X 7.00 X 8.800";

console.log(y.split(' X ').map(Number));

let x = "7.00 X .1875 X 8.800";

console.log(x.split(' X ').map(Number));

CodePudding user response:

From the above comment ...

The OP actually does not want "... to return this as an array of 3 numbers: 0.1875, 7.00, 8.800" but as an array of 3 stringified numbers with a sanitized/normalized number format "0.1875", "7.00", "8.800".

A possible approach was the combination of

  • fetching ... /(?<!\d)(?:\d*\.)?\d /g ... and ...
  • normalizing ... .replace(/^\./, '0$&') ... valid number formats.

const sampleData = `
  .1875 X 7.00 X 8.800 
  7.00 X .1875 X 8.800 
  .50" x 1.25" x 7.125" will make one part

  .1875 X 7.00 X 8.800 X 456 X 13.45.56.343.343.
`;

// see ... [(?<!\d)(?:\d*\.)?\d ]
const regXValidNumber = /(?<!\d)(?:\d*\.)?\d /g;

console.log(
  sampleData
    // retrieving the array of
    // valid stringified numbers.
    .match(regXValidNumber)
);
console.log(
  sampleData
    // retrieving the array of
    // valid stringified numbers.
    .match(regXValidNumber)
    // normalizing the number format.
    .map(str => str.replace(/^\./, '0$&'))
);
.as-console-wrapper { min-height: 100%!important; top: 0; }

  • Related