javascript比较字符串区分大小写

javascript compare strings case sensative

本文关键字:大小写 字符串区 比较 javascript      更新时间:2023-09-26

我想在两个字符串之间实现区分大小写的比较。以下是我到目前为止所做的,它运行得不太好

function compare(x,y){
  for (var i = 0; i < Math.min(x.length, y.length); i++){
  var xc = x[i];
  var yc = y[i];
  if (xc == yc) 
     continue;
  var xclow = x.toLowerCase();
  var yclow = y.toLowerCase();
    if (xclow == yclow)
        return xc < yc ? -1 : 1
    else
        return xclow  < yclow ? -1 : 1;
}

}

如果我做console.log(compare("Kk","kk"));,我得到的是-1,但如果我做了console.log(compare("Kka","kk"));,我得到了1,我不知道为什么。

为什么不只使用"Kk" === "kk"

function compare(x, y) {
    return x === y;
    // or return x === y ? 1 : -1
}

有两个打字错误,您写的是x.toLowerCase();而不是xc.toLowerCase();y.toLowerCase();而不是yc.toLowerCase();

function compare(x, y) {
    for (var i = 0; i < Math.min(x.length, y.length); i++) {
        var xc = x[i];
        var yc = y[i];
        if (xc == yc)
            continue;
        var xclow = xc.toLowerCase();
        var yclow = yc.toLowerCase();
        if (xclow == yclow)
            return xc < yc ? -1 : 1
        else
            return xclow < yclow ? -1 : 1;
        return x.length.localeCompare(y.length);
    }
}

顺便说一下,最后一个返回语句是不必要的,因为if和else都包含返回语句。

有更简单的方法可以做到这一点,但我认为你正在努力独自完成这一点。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare

类似于:

 console.log('a'.localeCompare('A', { sensitivity: 'variant' }));

如果需要,您可以添加区域设置等。