Home > OS >  How to ignore white space in string using regex?
How to ignore white space in string using regex?

Time:12-01

I am having a query string and I parse it and form array of objects like,

const regex = /((?:\bNOT\s )?\w )\s IN\s \('([^()]*)'\)/g;
const string = "DEVICE_SIZE IN ('036','048', '060','070') AND DEVICE_VOLTAGE IN ('1','3') AND NOT DEVICE_DISCHARGE_AIR IN ('S') AND NOT DEVICE_REFRIGERANT_CIRCUIT IN ('H', 'C')";
const data = Array.from(
  string.matchAll(regex), m =>
  ({
    [m[1]]: m[2].split("','")
  })
);
console.log(data);

Here ('036','048', '060','070') has a additional white space before 060, so the array formed looks like,

"DEVICE_SIZE": [
      "036",
      "048', '060",
      "070"
    ]

But expected result is

"DEVICE_SIZE": [
      "036",
      "048", 
      "060",
      "070"
    ]

Kindly help me to ignore all the white spaces before any string.

CodePudding user response:

You need to change your split pattern to get right output:

const regex = /((?:\bNOT\s )?\w )\s IN\s \('([^()]*)'\)/g;
const string = "DEVICE_SIZE IN ('036','048', '060','070') AND DEVICE_VOLTAGE IN ('1','3') AND NOT DEVICE_DISCHARGE_AIR IN ('S') AND NOT DEVICE_REFRIGERANT_CIRCUIT IN ('H', 'C')";
const data = Array.from(
  string.matchAll(regex), m =>
  ({
    [m[1]]: m[2].split(/',\s*'/)
  })
);
console.log(data);

Regex pattern /',\s*'/ will match closing ' and comma followed by 0 or more whitespaces and then opening ', this removing whitespaces from the resulting split array.

  • Related