JavaScript case insensitive string comparison

2018-12-31 04:43发布

How do I perform case insensitive string comparison in JavaScript?

18条回答
孤独总比滥情好
2楼-- · 2018-12-31 05:28

As said in recent comments, string::localCompare supports case insensitive comparisons (among other powerful things).

Here's a simple example

'xyz'.localeCompare('XyZ', undefined, { sensitivity: 'base' }); // returns 0

And a generic function you could use

function equalsIgnoringCase(text, other) {
    text.localeCompare(other, undefined, { sensitivity: 'base' }) === 0;
}

Note that instead of undefined you should probably enter the specific locale you are working with. This is important as denoted in the MDN docs

in Swedish, ä and a are separate base letters

Sensitivity options

Sensitivity options tabulated from MDN

Browser support

As of time of posting, UC Browser for Android and Opera Mini do not support locale and options parameters. Please check https://caniuse.com/#search=localeCompare for up to date info.

查看更多
梦寄多情
3楼-- · 2018-12-31 05:30

EDIT: This answer is 7 years old. Today you should use localeCompare.

Original answer

The best way to do a case insensitive comparison in JavaScript is to use RegExp match() method with the 'i' flag.

JavaScript: case-insensitive search

When both strings being compared are variables (not constants), then it's a little more complicated 'cause you need to generate a RegExp from the string but passing the string to RegExp constructor can result in incorrect matches or failed matches if the string has special regex characters in it.

If you care about internationalization don't use toLowerCase() or toUpperCase() as it doesn't provide accurate case-insensitive comparisons in all languages.

http://www.i18nguy.com/unicode/turkish-i18n.html

查看更多
查无此人
4楼-- · 2018-12-31 05:30

How about NOT throwing exceptions and NOT using slow regex?

return str1 != null && str2 != null 
    && typeof str1 === 'string' && typeof str2 === 'string'
    && str1.toUpperCase() === str2.toUpperCase();

The above snippet assumes you don't want to match if either string is null or undefined.

If you want to match null/undefined, then:

return (str1 == null && str2 == null)
    || (str1 != null && str2 != null 
        && typeof str1 === 'string' && typeof str2 === 'string'
        && str1.toUpperCase() === str2.toUpperCase());

If for some reason you care about undefined vs null:

return (str1 === undefined && str2 === undefined)
    || (str1 === null && str2 === null)
    || (str1 != null && str2 != null 
        && typeof str1 === 'string' && typeof str2 === 'string'
        && str1.toUpperCase() === str2.toUpperCase());
查看更多
只靠听说
5楼-- · 2018-12-31 05:32

Remember that casing is a locale specific operation. Depending on scenario you may want to take that in to account. For example, if you are comparing names of two people you may want to consider locale but if you are comparing machine generated values such as UUID then you might not. This why I use following function in my utils library (note that type checking is not included for performance reason).

function compareStrings (string1, string2, ignoreCase, useLocale) {
    if (ignoreCase) {
        if (useLocale) {
            string1 = string1.toLocaleLowerCase();
            string2 = string2.toLocaleLowerCase();
        }
        else {
            string1 = string1.toLowerCase();
            string2 = string2.toLowerCase();
        }
    }

    return string1 === string2;
}
查看更多
后来的你喜欢了谁
6楼-- · 2018-12-31 05:33

With the help of regular expression also we can achieve.

(/keyword/i).test(source)

/i is for ignore case. If not necessary we can ignore and test for NOT case sensitive match like

(/keyword/).test(source)
查看更多
弹指情弦暗扣
7楼-- · 2018-12-31 05:35

Suppose we want to find the string variable needle in the string variable haystack. There are three gotchas:

  1. Internationalized applications should avoid string.toUpperCase and string.toLowerCase. Use a regular expression which ignores case instead. For example, var needleRegExp = new RegExp(needle, "i"); followed by needleRegExp.test(haystack).
  2. In general, you might not know the value of needle. Be careful that needle does not contain any regular expression special characters. Escape these using needle.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");.
  3. In other cases, if you want to precisely match needle and haystack, just ignoring case, make sure to add "^" at the start and "$" at the end of your regular expression constructor.

Taking points (1) and (2) into consideration, an example would be:

var haystack = "A. BAIL. Of. Hay.";
var needle = "bail.";
var needleRegExp = new RegExp(needle.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), "i");
var result = needleRegExp.test(haystack);
if (result) {
    // Your code here
}
查看更多
登录 后发表回答