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?
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?'));
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.