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:20

if you are concerned about the direction of the inequality (perhaps you want to sort a list) you pretty-much have to do case-conversion, and as there are more lowercase characters in unicode than uppercase toLowerCase is probably the best conversion to use.

function my_strcasecmp( a, b ) 
{
    if((a+'').toLowerCase() > (b+'').toLowerCase()) return 1  
    if((a+'').toLowerCase() < (b+'').toLowerCase()) return -1
    return 0
}

Javascript seems to use locale "C" for string comparisons so the resulting ordering will be ugly if the strings contain other than ASCII letters. there's not much that can be done about that without doing much more detailed inspection of the strings.

查看更多
皆成旧梦
3楼-- · 2018-12-31 05:20

If both strings are of the same known locale, you may want to use Intl.Collator object like this:

function equalIgnoreCase(s1: string, s2: string) {
    return new Intl.Collator("en-US", { sensitivity: "base" }).compare(s1, s2) === 0;
}

Obviously, you may want to cache the Collator for better efficiency.

The advantages of this approach is that it should be much faster than using RegExps and is based on an extremely customizable (see description of locales and options constructor parameters in the article above) set of ready-to-use collators.

查看更多
残风、尘缘若梦
4楼-- · 2018-12-31 05:21

use regix for string match or comparison ,

in javaScript , you can use match() for string comparison , dont forget to put i in regix

example :

var matchString = "Test" ;
if(matchString.match(/test/i) ){
  alert('String matched) ;
}else{
 alert('String not matched') ;
}
查看更多
千与千寻千般痛.
5楼-- · 2018-12-31 05:24

There are two ways for case insensitive comparison:

  1. Convert strings to upper case and then compare them using the strict operator (===). How strict operator treats operands read stuff at: http://www.thesstech.com/javascript/relational-logical-operators
  2. Pattern matching using string methods:

Use the "search" string method for case insensitive search. Read about search and other string methods at: http://www.thesstech.com/pattern-matching-using-string-methods

<!doctype html>
  <html>
    <head>
      <script>

        // 1st way

        var a = "apple";
        var b = "APPLE";  
        if (a.toUpperCase() === b.toUpperCase()) {
          alert("equal");
        }

        //2nd way

        var a = " Null and void";
        document.write(a.search(/null/i)); 

      </script>
    </head>
</html>
查看更多
情到深处是孤独
6楼-- · 2018-12-31 05:24

Lots of answers here, but I like to add a sollution based on extending the String lib:

String.prototype.equalIgnoreCase = function(str)
{
    return (str != null 
            && typeof str === 'string'
            && this.toUpperCase() === str.toUpperCase());
}

This way you can just use it like you do in Java!

Example:

var a = "hello";
var b = "HeLLo";
var c = "world";

if (a.equalIgnoreCase(b)) {
    document.write("a == b");
}
if (a.equalIgnoreCase(c)) {
    document.write("a == c");
}
if (!b.equalIgnoreCase(c)) {
    document.write("b != c");
}

Output will be:

"a == b"
"b != c"

String.prototype.equalIgnoreCase = function(str) {
  return (str != null &&
    typeof str === 'string' &&
    this.toUpperCase() === str.toUpperCase());
}


var a = "hello";
var b = "HeLLo";
var c = "world";

if (a.equalIgnoreCase(b)) {
  document.write("a == b");
  document.write("<br>");
}
if (a.equalIgnoreCase(c)) {
  document.write("a == c");
}
if (!b.equalIgnoreCase(c)) {
  document.write("b != c");
}

查看更多
临风纵饮
7楼-- · 2018-12-31 05:26

Since no answer clearly provided a simple code snippet for using RegExp, here's my attempt:

function compareInsensitive(str1, str2){ 
  return typeof str1 === 'string' && 
    typeof str2 === 'string' && 
    new RegExp("^" + str1.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') + "$", "i").test(str2);
}

It has several advantages:

  1. Verifies parameter type (any non-string parameter, like undefined for example, would crash an expression like str1.toUpperCase()).
  2. Does not suffer from possible internationalization issues.
  3. Escapes the RegExp string.
查看更多
登录 后发表回答