Reputation: 1915
I want to implement a case sensitive comparison between 2 string. Here's what I have done so far, it is not working so well
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;
}
}
if im doing console.log(compare("Kk","kk"));
I'm getting -1 as expected,but if i'm doing console.log(compare("Kka","kk"));
i'm getting 1 and i don't know why.
Upvotes: 0
Views: 73
Reputation: 1493
There was two typo, you had written x.toLowerCase();
instead of xc.toLowerCase();
and y.toLowerCase();
instead of 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);
}
}
By the way, last return statement is unnecessary since both if and else contains return statement.
There are more simpler ways to do that but I think you're trying to accomplish that on your own.
Upvotes: 1
Reputation: 1748
Why not use just "Kk" === "kk"
?
function compare(x, y) {
return x === y;
// or return x === y ? 1 : -1
}
Upvotes: 3
Reputation: 18536
Something like:
console.log('a'.localeCompare('A', { sensitivity: 'variant' }));
You can add the locale if you need etc.
Upvotes: 0