我如何在不使用 toUpperCase 的情况下大写

How i can Capitalize without using toUpperCase

如何在不使用 .toUpperCase() ... string.prototype.capitalize 或 Regex 的情况下将单词大写?

只有单词的第一个字母。

我有这个,而且效果很好:

text.charAt(0).toUpperCase() + text.slice(1);

但我不想使用 .toUpperCase()。

PD:只用JS,不用CSS。

谢谢。

您可以使用fromCharCode and charCodeAt在大小写字母之间切换:

function capitalize(word) {
    var firstChar = word.charCodeAt(0);
    if (firstChar >= 97 && firstChar <= 122) {
        return String.fromCharCode(firstChar - 32) + word.substr(1);
    }
    return word;
}

alert(
    capitalize("abcd") + "\n" +
    capitalize("ABCD") + "\n" +
    capitalize("1bcd") + "\n" +
    capitalize("?bcd")
);

function capitalise(word){
    let asciiRef = word.charCodeAt(0);
    let newAsciiRef = asciiRef - 32;
    let newChar = String.fromCharCode(newAsciiRef);
    return newChar + word.substr(1);
}

取自asii case conversion trick

使用位运算符检查以下实现

代码:

function toUpperCase(str) {
    var asciiCode = str.charCodeAt(0);
    if (asciiCode > 96 && asciiCode < 123) {
        // & ~(1 << 5) set the 6th bit to 1
        return String.fromCharCode(asciiCode & ~(1 << 5)) + str.slice(1);
    } else {
        return str;
    }
}

说明

To convert the lowercase alphabet to uppercase, we can xor the 6th bit

如果您查看字符 a..z,您会发现所有字符的第 6 位都设置为 1。

a = 01100001    A = 01000001 
b = 01100010    B = 01000010 
c = 01100011    C = 01000011 
d = 01100100    D = 01000100 
e = 01100101    E = 01000101 
f = 01100110    F = 01000110 
g = 01100111    G = 01000111 
h = 01101000    H = 01001000 
i = 01101001    I = 01001001 
j = 01101010    J = 01001010 
k = 01101011    K = 01001011 
l = 01101100    L = 01001100 
m = 01101101    M = 01001101 
n = 01101110    N = 01001110 
o = 01101111    O = 01001111 
p = 01110000    P = 01010000 
q = 01110001    Q = 01010001 
r = 01110010    R = 01010010 
s = 01110011    S = 01010011 
t = 01110100    T = 01010100 
u = 01110101    U = 01010101 
v = 01110110    V = 01010110 
w = 01110111    W = 01010111 
x = 01111000    X = 01011000 
y = 01111001    Y = 01011001 
z = 01111010    Z = 01011010