简体   繁体   English

匹配字符串不区分大小写

[英]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.在 JavaScript 中,字符串比较区分大小写。

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.使用带有i标志的 ReGex 使其不区分大小写。

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:根据您的使用情况,它可以方便地使用正则表达式匹配与i的标志,使之区分敏感,就像这样:

'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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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