如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
当前回答
首頁 〉外文書 〉文學 〉文學 〉Capitalize First Word: Shortest
text.replace(/(^.)/, m => m.toUpperCase())
每一个字:最短
text.replace(/(^\w|\s\w)/g, m => m.toUpperCase());
如果你想确保剩下的在底部:
text.replace(/(^\w|\s\w)(\S*)/g, (_,m1,m2) => m1.toUpperCase()+m2.toLowerCase())
其他回答
对于另一个案例,我需要它来资本化第一封信,下载其余的案例,下列案例让我改变了这个功能:
//es5
function capitalize(string) {
return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
}
capitalize("alfredo") // => "Alfredo"
capitalize("Alejandro")// => "Alejandro
capitalize("ALBERTO") // => "Alberto"
capitalize("ArMaNdO") // => "Armando"
// es6 using destructuring
const capitalize = ([first,...rest]) => first.toUpperCase() + rest.join('').toLowerCase();
我最近在一个项目中需要类似的功能,这就是我如何实施它:
函数 capitlizeFirst(str) { // checks for null, undefined and empty string if (!str) return; return str.match("^[a-z]")? str.charAt(0).toUpperCase() + str.substring(1) : str; } console.log(capitlizeFirst("")); console.log(capitlizeFirst(null)); console.log(capitlizeFirst(undefined)); console.log(capitlizeFirst("hello world")); console.log(capitlizeFirst("/index.html"));
我們可以獲得第一個角色與我最喜歡的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();
});
};
如果您已经(或正在考虑)使用Lodash,解决方案很容易:
_.upperFirst('fred');
// => 'Fred'
_.upperFirst('FRED');
// => 'FRED'
_.capitalize('fred') //=> 'Fred'
查看他们的文档: https://lodash.com/docs#capitalize
_.camelCase(“Foo Bar”); //=>“FooBar”
https://lodash.com/docs/4.15.0#camelCase
_.lowerFirst('Fred');
// => 'fred'
_.lowerFirst('FRED');
// => 'fRED'
_.snakeCase('Foo Bar');
// => 'foo_bar'
Vanilla JavaScript for first up 案例:
function upperCaseFirst(str){
return str.charAt(0).toUpperCase() + str.substring(1);
}
如果您想修改全覆文本,您可能希望修改其他例子如下:
function capitalize (text) {
return text.charAt(0).toUpperCase() + text.slice(1).toLowerCase();
}
这将确保下列文本进行更改:
TEST => Test
This Is A TeST => This is a test