0
votes

Trying to compare two strings lexicographically in google apps scripts.

str.compareTo() doesnt work... Is there another way to do this? I've searched through many answers on stack and on the google apps script docs couldn't find a solution.

2

2 Answers

1
votes
a.localeCompare(b)

This will return 1 or -1 depending on which string is lexicographically greater.

  • Directly comparing both strings would also work:
a > b

This will return true or false.

Reference:

0
votes

I don't know if theres a way to do it, in any case here is a custom function that'll do it.

function StringCompare(a, b) {
   var aLength = a.length;
   var bLength = b.length;
   var minLength = Math.min(aLength, bLength);

   for (i = 0; i < minLength; i++) {
       if (a.charAt(i) > b.charAt(i)) return 1;
       if (a.charAt(i) < b.charAt(i)) return -1;
   }

   if (aLength > bLength) return 1;
   if (aLength < bLength) return -1;
   return 0;
}