如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
当前回答
好吧,这里是一个更简单的方法,空间线和这一切。
首先,你應該知道,一條線是一系列字符。
这个答案应该在所有空间线上工作。
假设你的字符串在一个变量 yourString:
const yourString = "el salvacion sucks" const capitalizeString = yourString.split(" ").长度 > 0? yourString.split(" ").map((item) => 项目[0].toUpperCase() + 项目.substring(1)).join(" ") : yourString[0].toUpperCase() + yourString.substring(1) console.log(capitalizeString)
点击 Run Code Snippet 按钮查看结果
其他回答
我在我的开发环境中使用这些线路,特别是当我与HTTP等API合作时:
假设您有一个 HTTP 标题,您希望在其名义中资本化每个初始字母,并在其组成词之间添加混合物。
'access control allow origin'
.replace(/\b\w/g, function (match) {
return match.toUpperCase();
})
.split(' ')
.join('-');
// Output: 'Access-Control-Allow-Origin'
这可能不是最优雅和最有吸引力的功能定义,但它肯定会完成工作。
如果您使用 Underscore.js 或 Lodash, underscore.string 图书馆提供链接扩展,包括资本化:
_.capitalize(string) 将序列的第一字母转换为顶端。
例子:
_.capitalize("foo bar") == "Foo bar"
使用 RamdaJs 的另一种方式,是功能编程方式:
firstCapital(str){
const fn = p => R.toUpper(R.head(p)) + R.tail(p);
return fn(str);
}
用多个字在一个字符串:
firstCapitalAllWords(str){
const fn = p => R.toUpper(R.head(p)) + R.tail(p);
return R.map(fn,R.split(' ', str)).join(' ');
}
我們可以獲得第一個角色與我最喜歡的RegExp之一,看起來像一個可愛的微笑: /^./
String.prototype.capitalize = function () {
return this.replace(/^./, function (match) {
return match.toUpperCase();
});
};
对于所有咖啡豆:
String::capitalize = ->
@replace /^./, (match) ->
match.toUpperCase()
...和所有认为有更好的方式做到这一点的男孩,没有扩展原生原型:
var capitalize = function (input) {
return input.replace(/^./, function (match) {
return match.toUpperCase();
});
};
使用此 Node.js 模块, http://stringjs.com/ 包,以资本化您的行:
var S = require('string');
S('jon').capitalize().s; //'Jon'
S('JP').capitalize().s; //'Jp'