Alv*_*lez 1 javascript capitalize
如何在不使用 .toUpperCase() ... string.prototype.capitalize 或 Regex 的情况下将单词大写?
只有单词的第一个字母。
我有这个,并且完美运行:
text.charAt(0).toUpperCase() + text.slice(1);Run Code Online (Sandbox Code Playgroud)
但我不想使用 .toUpperCase()。
PD:只使用 JS,不使用 CSS。
谢谢。
您可以使用fromCharCode和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")
);Run Code Online (Sandbox Code Playgroud)