如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
当前回答
这是一个简单的
const upper = lower.replace(/^\w/, c => c.toUpperCase());
其他回答
首先,我只是想清楚资本化在这个背景下意味着什么,“这条线是资本化”可靠的来源
你可以从例子中看到,只要这不是OP正在寻找的东西,它应该说的是“我如何制作一条线的第一字”(不资本化线)
function ucfirst (str) {
return typeof str != "undefined" ? (str += '', str[0].toUpperCase() + str.substr(1)) : '';
}
解释
typeof str != "undefined" // Is str set
? // true
str += '' // Turns the string variable into a string
str[0].toUpperCase() // Get the first character and make it upper case
+ // Add
str.substr(1) // String starting from the index 1 (starts at 0)
: // false
''; // Returns an empty string
这将与任何论点或没有论点工作。
undefined === ""
"" === ""
"my string" === "My string"
null === "Null"
undefined === "";
false === "False"
0 === "0"
true === "True"
[] === ""
[true,0,"",false] === "True,0,,false"
在 CoffeeScript 中,添加一个字符串的原型:
String::capitalize = ->
@substr(0, 1).toUpperCase() + @substr(1)
使用将是:
"woobie".capitalize()
谁得益:
"Woobie"
如果你去其中一个 regex 答案,请记住,它们只会与 ASCII 字符一起工作. 所有的 Unicode 字母都不会被打破. XRegExp 图书馆和其 Unicode 插件解决这个问题,如果你想与 regex 保持。
String.prototype.capitalize = function () {
return this.replace(XRegExp("^\\p{L}"), function ($0) { return $0.toUpperCase(); })
}
考虑到它仍然不涵盖所有可能性(混合字符,见 http://www.regular-expressions.info/unicode.html),似乎更容易使用.charAt(0).toUpperCase() 方法。
我们将使用CSS来实现这一点,它也可以从外部CSS设置。
<span text-transform="capitalize ">The first letter of each word becomes an upper case</span>
使用Vanilla JavaScript,我们可以:
let string = "test case"
string = string[0].toUpperCase() + string.substring(1)
//return "Test case"
此分類上一篇:</b/>
字符串[0].toUpperCase():将字符串中的第一个字符转换为顶部字符串
string.substring(1):在行中删除第一个字母并返回剩余的字符
text-transform="capitalize":在这个标签的顶部字母中创建每个字母的第一个字母. 如果您使用“uppercase”作为文本转换的值,标签中的每个字母将是一个字母。
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
一些其他答案修改 String.prototype(这个答案也被用来),但我会建议反对这一点现在由于可持续性(很难找到函数在哪里被添加到原型,如果另一个代码使用相同的名称 / 一个浏览器添加一个原始函数与相同的名称在未来可能导致冲突)。