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

例如:

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


当前回答

s[0].toUpperCase``+s.substr`1`

let s = 'hello there' console.log( s[0].toUpperCase''+s.substr`1` )

其他回答

yourString.replace(/^[a-z]/, function(m){ return m.toUpperCase() });

(您可以将其嵌入到函数中,或者甚至将其添加到 String 原型中,如果您经常使用它。

一个小改进 - 每个字在标题。

String.prototype.toTitleCase = function(){
    return this.replace(/\b(\w+)/g, function(m,p){ return p[0].toUpperCase() + p.substr(1).toLowerCase() });
}

var s = 'heLLo, wOrLD!';
console.log(s.toTitleCase()); // Hello, World!

使用此 Node.js 模块, http://stringjs.com/ 包,以资本化您的行:

var S = require('string');
S('jon').capitalize().s; //'Jon'
S('JP').capitalize().s; //'Jp'
function capitalizeFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
}

一些其他答案修改 String.prototype(这个答案也被用来),但我会建议反对这一点现在由于可持续性(很难找到函数在哪里被添加到原型,如果另一个代码使用相同的名称 / 一个浏览器添加一个原始函数与相同的名称在未来可能导致冲突)。

var capitalizeMe = "string not starting with capital"

资本化与substr

var capitalized = capitalizeMe.substr(0, 1).toUpperCase() + capitalizeMe.substr(1);