javascript 中区分大小写的排序,其中所有大写字母都位于所有小写字母之前

msh*_*adi 5 javascript sorting case-sensitive

我需要以大写字母在前的方式对两个字符串进行排序,即使对于不同的字母也是如此,例如:

先于蚂蚁

CD出现在CD之前

我可以使用 localCompare 进行这样的排序吗?

const sortString = (a, b) => String(a).localeCompare(b);
Run Code Online (Sandbox Code Playgroud)

Mik*_*yen -1

如果第一个字符串大于,我的函数返回 1;如果第一个字符串小于,则返回 -1;如果等于第二个字符串,则返回 0。

// return value like compare function
const findCompareValue = (flag) => {
  if (flag) {
    return -1;
  } else {
    return 1;
  }
}

const compareCaseSensitive = (a, b) => {
  // find min length just in case two string don't have the same length
  const minLen = a.length > b.length ? b.length : a.length;
  let i = 0;

  const minLowerCaseCharCode = 97;
  const maxLowerCaseCharCode = 122;
  const minUpperCaseCharCode = 65;
  const maxUpperCaseCharCode = 90;

  while (true && i !== minLen) {
    // get char code
    const aCharCode = a[i].charCodeAt();
    const bCharCode = b[i].charCodeAt();

    // check whether character is uppercase
    const isACharUpperCase = minUpperCaseCharCode <= aCharCode && aCharCode <= maxUpperCaseCharCode;
    const isBCharUpperCase = minUpperCaseCharCode <= bCharCode && bCharCode <= maxUpperCaseCharCode;

    if (isACharUpperCase) {
      if (isBCharUpperCase  && bCharCode !== aCharCode) {
        // two characters are uppercase and different
        return findCompareValue(aCharCode < bCharCode);
      } else if (aCharCode !== bCharCode) {
        // second character is lowercase
        return 1;
      }
    } else {
      if (isBCharUpperCase) {
        // second string is uppercase
        return -1;
      } else if (aCharCode !== bCharCode) {
        // two characters are lowercase and different
        return findCompareValue(aCharCode < bCharCode);
      }
    }

    i += 1;
  }

  return 0;
}

const a = 'CD';
const b = 'cD';

console.log('result', compareCaseSensitive(a, b));
Run Code Online (Sandbox Code Playgroud)