javascriptstringsubstringindexofrhino

How to compare two strings case insensitive in Rhino js


I intend to check if a string is a substring of another string. However, case insensitive match is not possible since toLowerCase() and toUpperCase() methods are not supported in Rhino 1.7.13.

var stored_string="{{SSHA1}9BC34549D565D9505B287DE0CD20AC77BE1D3F2C"
var str = "9bc34549d565d9505b287de0cd20ac77be1d3f2c"

I am using indexOf mathod to check for the substring.

if (stored_string.toString().indexOf(str)===0) {
   //do something
}

Is there any good way this comparison is possible case insensitive?


Solution

  • Here's a toLowerCase polyfill that should work. I'm unsure of all the restrictions of rhino, but this should work for standard ASCII characters a-z and A-Z

    function toLowerCase(str) {
      var output = "";
      for (let i = 0; i < str.length; i++) {
        if (str.charCodeAt(i) >= 65 && str.charCodeAt(i) <= 90) {
          output += String.fromCharCode(str.charCodeAt(i) + 32);
        } else {
          output += str[i];
        }
      }
      return output;
    }
    
    console.log(toLowerCase(prompt("Enter a string")));

    so we can use that here:

    function toLowerCase(str) {
      var output = "";
      for (let i = 0; i < str.length; i++) {
        if (str.charCodeAt(i) >= 65 && str.charCodeAt(i) <= 90) {
          output += String.fromCharCode(str.charCodeAt(i) + 32);
        } else {
          output += str[i];
        }
      }
      return output;
    }
    
    var stored_string="{{SSHA1}9BC34549D565D9505B287DE0CD20AC77BE1D3F2C"
    var str = "9bc34549d565d9505b287de0cd20ac77be1d3f2c"
    
    console.log(toLowerCase(stored_string).indexOf(toLowerCase(str)) !== -1 || toLowerCase(str).indexOf(toLowerCase(stored_string)) !== -1);