【问题标题】:How i can Capitalize without using toUpperCase [closed]我如何在不使用 toUpperCase 的情况下大写 [关闭]
【发布时间】:2017-06-24 14:35:06
【问题描述】:

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

只有单词的第一个字母。

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

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

但我不想使用 .toUpperCase()。

PD:只使用 JS,不使用 CSS。

谢谢。

【问题讨论】:

  • 需要什么?
  • 可以在 css 中使用 text-transform:capitalize via
  • @PranavCBalan 刚刚学习
  • 反问:为什么要编写自己的,可能会浪费资源的函数,而不是使用已经存在的内部函数?
  • 自从他更新后,我将我的评论修改为 - 不要这样做,如果你想实现它重写语言......

标签: javascript capitalize


【解决方案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;
    }
}

说明

要将小写字母转换为大写,我们可以对第 6 位进行异或操作

如果您查看字符 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 

【讨论】:

  • Hello, world! 怎么样!
  • @ibrahimmahrir 用位运算符更新了答案
【解决方案2】:

您可以使用fromCharCodecharCodeAt在大小写之间切换:

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")
);

【讨论】:

  • 该死的,打败我。反正你的更优雅
  • @ibrahimmahrir 它会输出Hello i was born in the 90s!!!,你可能已经知道了。
  • 是的,对编辑很抱歉,我刚刚测试并错误地按下了按钮。如果字符串以数字开头,您的代码将失败!大写:90s kids!!
  • 如果字符串以任何非字母开头的字符串也会失败...
  • @Connum 同意!!我只是给他举个例子!
【解决方案3】:
function capitalise(word){
    let asciiRef = word.charCodeAt(0);
    let newAsciiRef = asciiRef - 32;
    let newChar = String.fromCharCode(newAsciiRef);
    return newChar + word.substr(1);
}

【讨论】:

  • 你应该解释你的代码是如何工作的,它将如何回答问题,以及它可能有哪些缺点,例如。没有正确大写有效的非 ASCII 字母字符,并且对于小写 ASCII 字符以外的任何字符通常具有未定义的行为。
猜你喜欢
  • 1970-01-01
  • 2012-08-19
  • 1970-01-01
  • 2019-10-08
  • 2012-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多