Home > Enterprise >  How to get the words before a certain character when the dataset rows may and may not contain that c
How to get the words before a certain character when the dataset rows may and may not contain that c

Time:02-27

The result I get now gives me blank when that character is not there:

Code

const categories = catSubSheet.getRange(2, 1, catSubSheet.getLastRow() - 1, 3).getValues();
let categories1 = categories.filter(e => e[0] != '').map(function (e) { return e[0] });

let sheetsToProcess = [];
  for (let a = 0; a < categories1.length; a  ) {
    sheetNames = categories1[a].substring(0, categories1[a].indexOf(" ("));
    sheetsToProcess.push('BOQ '   sheetNames)
  }

Data

[
 [GF HTG SHEET 1 (Drawing)],
 [GF HTG SHEET 2 (Drawing)],
 [GF DWS SHEET 1],
]

The result

Sheets to Process: BOQ GF HTG SHEET 1,BOQ GF HTG SHEET 2,BOQ

Expected Result

Sheets to Process: BOQ GF HTG SHEET 1,BOQ GF HTG SHEET 2,BOQ GF DWS SHEET 1

CodePudding user response:

As a quick fix you can try this:

...

let sheetsToProcess = [];
  for (let a = 0; a < categories1.length; a  ) {
    var index = categories1[a].indexOf(" (");
    if (index > -1) { sheetNames = categories1[a].substring(0,index) }
    else { sheetNames = categories1[a] }
    sheetsToProcess.push('BOQ '   sheetNames)
  }

...

But actually it can be done in more neat way.

Something like this:

var categories1 = [
    'GF HTG SHEET 1 (Drawing)',
    'GF HTG SHEET 2 (Drawing)',
    'GF DWS SHEET 1'
];

var sheetsToProcess = categories1.map(x => 'BOQ '   x.replace(/ \(. $/, ''));

console.log(sheetsToProcess); // [ 'BOQ GF HTG SHEET 1', 'BOQ GF HTG SHEET 2', 'BOQ GF DWS SHEET 1' ]

  • Related