0

Is there an easy way to make all string compares in a js file case-insensitive? Here's a simple example of a normal check:

var message = 'This is a Test';
var isTest = message.toLowerCase().indexOf('test') > -1;

This isn't a bad approach for a single check but it gets verbose if it needs to be done 10+ times in a file. Is there an easier way to make string compares case-insensitive for the entire scope of a js file?

j08691
  • 204,283
  • 31
  • 260
  • 272
Jim Platts
  • 25
  • 6
  • 2
    wrap it in a function, and then call the function throughout your file. – RJM Oct 14 '16 at 16:42
  • 1
    [RegExp](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) can make case-insensitive test. – Teemu Oct 14 '16 at 16:44
  • Possible duplicate of [JavaScript: case-insensitive search](http://stackoverflow.com/questions/177719/javascript-case-insensitive-search) – Neo Oct 14 '16 at 16:48

2 Answers2

0

Write your own function and use that everywhere.

function contains(a, b) {
  return a.toLowerCase().indexOf(b.toLowerCase()) > -1;
}

console.log(contains('This is a Test', 'test'));
console.log(contains('ABC', 'abc'));
console.log(contains('ABCdefGHI', 'Fgh'));
console.log(contains('Nope, no match', 'See?'));
Mike Cluck
  • 31,869
  • 13
  • 80
  • 91
0

I see two options:

1- Regex with i to make it case-insensitive

/test/i.test(message)

2- Make a function that does that, with the possibility of assigning it to the String object

// wrapper function
function iIncludes(needle, haystack) {
  return haystack.toLowerCase().indexOf(needle) >= 0;
}
iIncludes('test', 'This is a Test') // returns true

// attached to the String prototype
if (!String.prototype.iIncludes) {
  String.prototype.iIncludes = function(needle) {
    return this.toLowerCase().indexOf(needle) >= 0;
  }
}
'This is a Test'.iIncludes('test') // returns true

As an aside, if you can use ES6 features (not compatible with all browsers), there's a "better" method than indexOf, see includes

jonathanGB
  • 1,500
  • 2
  • 16
  • 28