简体   繁体   中英

Matching Strings to be case insensitive

In my application I have status of an event. I have created an object for those status while writing test scripts like this:

var satus = {
open : 'Open',
inProgress : 'In-Progress'
closed : 'Closed'
};

I have that status displayed in many pages of the application and at different pages it is written in Upper Case letters while not in others.

Can we expect Strings as insensitive?

In JavaScript, string comparison is case sensitive.

You can compare two strings case insensitively with the following code.

var equal = str1.toUpperCase() === str2.toUpperCase();

Do you want like this?

for(var key in status) {
    var value = status[key].toLowerCase();
    console.log(value);
}

Use ReGex with the i flag to make it case insensitive.

Depending on your use-case, it may be convenient to use a RegEx matcher with the i flag to make it case- in sensitive, like so:

'Test'.match(/test/)  //=> null
'Test'.match(/test/i) //=> ["Test", index: 0, input: "Test", groups: undefined]

This works especially well when wanting to do partial matches:

'Test'.match(/te/)  //=> null
'Test'.match(/te/i) //=> ["Te", index: 0, input: "Test", groups: undefined]

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM