如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?

例如:

“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”


当前回答

对于另一个案例,我需要它来资本化第一封信,下载其余的案例,下列案例让我改变了这个功能:

//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();

其他回答

最简单的解决方案是:

let yourSentence = 'it needs first letter upper case';

yourSentence.charAt(0).toUpperCase() + yourSentence.substr(1);

或:

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

或:

yourSentence.substr(0, 1).toUpperCase() + yourSentence.substr(1);

这是一个简单的

const upper = lower.replace(/^\w/, c => c.toUpperCase());

如果你想在一个字符串中资本化每一个字,你可以使用以下字符串:

'all_lowercase Capitalized lower_then_Upper a'.replace(/(?<=\b)[a-z](?=\w*)/g, c => c.toUpperCase())
// prints "All_lowercase Capitalized Lower_then_Upper A"
yourString.replace(/\w/, c => c.toUpperCase())

我发现这支箭的功能是最容易的。 替换符合你的字符的第一个字符(\w)字符,并将其转换为顶端。

将所有单词的第一字母分为一个字符串:

function capitalize(str) {
  return str.split(' ').map(word => word.charAt(0).toUpperCase() + word.toLowerCase().slice(1)).join(' ');
}