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

例如:

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


当前回答

只是因为这是一个真正的单线,我会包括这个答案. 这是一个基于ES6的交叉线单线。

let setStringName = 'the Eiffel Tower';
setStringName = `${setStringName[0].toUpperCase()}${setStringName.substring(1)}`;

其他回答

这是一个简单的

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

咖啡文字

ucfirst = (str) -> str.charAt(0).toUpperCase() + str.slice(1)

作为一个严格的原型方法:

String::capitalize = -> @charAt(0).toUpperCase() + @slice(1)

使用:

var str = “ruby java”; console.log(str.charAt(0).toUpperCase() + str.substring(1));

它将输出“Ruby java”到控制台。

如果您想修改全覆文本,您可能希望修改其他例子如下:

function capitalize (text) {
    return text.charAt(0).toUpperCase() + text.slice(1).toLowerCase();
}

这将确保下列文本进行更改:

TEST => Test
This Is A TeST => This is a test
function capitalize(s) {
    // returns the first letter capitalized + the string from index 1 and out aka. the rest of the string
    return s[0].toUpperCase() + s.substr(1);
}


// examples
capitalize('this is a test');
=> 'This is a test'

capitalize('the Eiffel Tower');
=> 'The Eiffel Tower'

capitalize('/index.html');
=> '/index.html'