0

I would appreciate some guidance on where my error is.

At the moment, my code finds the word 'he' perfectly and replaces it with 'she'; however for some reason it ignores 'He' with a capital letter at the start of a sentence and replaces it with 'undefined'. I have included the global flag 'i' to ignore case sensitivity, but still, it does not work.

Here is my code:

var mapObj = {
      Childname : name,
      SchoolName : schoolName,
      he : 'she',
      his : 'her',
      him : 'her',
      himself : 'herself',
      she : 'he',
      her : 'his',
      herself : 'himself',
      boy : 'girl'
    };

Here is where the error likely is.

    for (var n = 0; n<data.length;n++) {
      let pattern = (gender === 'Male') ? new RegExp (/\b(Childname|SchoolName|she|her|herself|girl)\b/,'gi') : new RegExp(/\b(Childname|he|him|his|himself|boy)\b/,'gi')
      let changed = data[n][0].replace(pattern, function(matched){
        return mapObj[matched];
          });
          changedComments.push([changed])
          }
          destinationSheet.getRange(1,1,changedComments.length,changedComments[0].length).setValues(changedComments)

Any help here would be greatly appreciated.

Thank you!

lmcc
  • 63
  • 7

2 Answers2

0

The value of matched will be the substring that matches the pattern that you provide, so if your pattern is /he/gi, and the matched substring is He, then the returned substring match will still be He, which doesn't exist as a key in matchObj.

The simple way to fix this would be

let changed = data[n][0].replace(pattern, function(matched){
  return mapObj[matched.toLowerCase()];
});
George D.
  • 255
  • 2
  • 10
0

It is beeing replaced with undefined because the match is He not he and you are returning return mapObj[matched]; - so return mapObj['He']; - which is undefined.

return mapObj[matched.toLowerCase()]; would work, but then your replaced text would start with a lowercase she. So you should also add a check if the first letter is uppeercase like here for example and then uppercase the first letter of your replacement like here if its required.

marks
  • 1,501
  • 9
  • 24